multi-pag tif to several jpeg files (java) - java

Hello I was able to convert a tif file to jpeg with the following code that I got from
https://stackoverflow.com/questions/15429011/how-to-convert-tiff-to-jpeg-png-in-java#=
String inPath = "./tifTest/113873996.002.tif";
String otPath = "./tifTest/113873996.002-0.jpeg";
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(inPath), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(new FileOutputStream(otPath), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TifToJpeg.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TifToJpeg.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This only works with one-page tif file, and when I use it with a multi-page tif, it only saves the first page.
How can I modified this to save a mymultipagetif.tif into:
mymultipagetif-0.jpeg
mymultipagetif-1.jpeg
mymultipagetif-2.jpeg
Thanks!

This will takes a multi-page TIFF file (in the SeekableStream), extract the pages in the pages array ("1", "3", "4" for example) and write them into a single multi-page tiff into the file outTIffFileName. Modify as desired.
private String _ExtractListOfPages (SeekableStream ss, String outTiffFileName, String[] pages){
// pageNums is a String array of 0-based page numbers.
try {
TIFFDirectory td = new TIFFDirectory(ss, 0);
if (debugOn) {
System.out.println("Directory has " + Integer.toString(td.getNumEntries()) + " entries");
System.out.println("Getting TIFFFields");
System.out.println("X resolution = " + Float.toString(td.getFieldAsFloat(TIFFImageDecoder.TIFF_X_RESOLUTION)));
System.out.println("Y resolution = " + Float.toString(td.getFieldAsFloat(TIFFImageDecoder.TIFF_Y_RESOLUTION)));
System.out.println("Resolution unit = " + Long.toString(td.getFieldAsLong(TIFFImageDecoder.TIFF_RESOLUTION_UNIT)));
}
ImageDecoder decodedImage = ImageCodec.createImageDecoder("tiff", ss, null);
int count = decodedImage.getNumPages();
if (debugOn) { System.out.println("Input image has " + count + " page(s)"); }
TIFFEncodeParam param = new TIFFEncodeParam();
TIFFField tf = td.getField(259); // Compression as specified in the input file
param.setCompression(tf.getAsInt(0)); // Set the compression of the output to be the same.
param.setLittleEndian(false); // Intel
param.setExtraFields(td.getFields());
FileOutputStream fOut = new FileOutputStream(outTiffFileName);
Vector<RenderedImage> vector = new Vector<RenderedImage>();
RenderedImage page0 = decodedImage.decodeAsRenderedImage(Integer.parseInt(pages[0]));
BufferedImage img0 = new BufferedImage(page0.getColorModel(), (WritableRaster)page0.getData(), false, null);
int pgNum;
// Adding the extra pages starts with the second one on the list.
for (int i = 1; i < pages.length; i++ ) {
pgNum = Integer.parseInt(pages[i]);
if (debugOn) { System.out.println ("Page number " + pgNum); }
RenderedImage page = decodedImage.decodeAsRenderedImage(pgNum);
if (debugOn) { System.out.println ("Page is " + Integer.toString(page.getWidth()) + " pixels wide and "+ Integer.toString(page.getHeight()) + " pixels high."); }
if (debugOn) { System.out.println("Adding page " + pages[i] + " to vector"); }
vector.add(page);
}
param.setExtraImages(vector.iterator());
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", fOut, param);
if (debugOn) { System.out.println("Encoding page " + pages[0]); }
encoder.encode(decodedImage.decodeAsRenderedImage(Integer.parseInt(pages[0])));
fOut.close();
} catch (Exception e) {
System.out.println(e.toString());
return("Not OK " + e.getMessage());
}
return ("OK");
}

Related

Extract binaries line by line in JAVA without saving to a string

I have the following method, but this one has a problem and it is that in a part of the file there are some special characters where the character with hexadecimal value 81(.) when the program generates the export of the file is 3F(?) and with that it damages the binary:
public static void exportbinary() {
List<String> files = listFiles(source,1);
System.out.println("Reviewing files to extract data");
String registro = null;
String contenido = "";
for (String s : files) {
//The name of the files to be processed is adjusted
String ogName=s;
System.out.println("Renaming files to extract binary data...");
File sFile = new File(source, s);
sFile.renameTo(new File(source,s+"ext"));
s = s+"ext";
//Start binary extraction process
File sourceFile = new File(source, s);
File destFile = new File(destination, ogName);
if (destFile.exists()) {
destFile.delete();
}
if (!dctmp.exists()) {
try {
dctmp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Writer w = null;
try {
w = new BufferedWriter(new FileWriter(dctmp, true));
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("Processing" + sourceFile + " en " + destFile);
try (BufferedReader br = new BufferedReader(new FileReader(sourceFile))) {
String data;
while ((data = br.readLine()) != null) {
String line = data;
if (line.substring(0, 6).equals("924007")) {
// Valores binarios
String binarios = line.substring(585, 586 + 82);
line = line.substring(0, 585) + (new String(new char[83]).replace('\0', '0'))
+ line.substring((586 + 82), line.length());
// TID
String TID = line.substring(1005, 1020);
registro = TID + ";" + binarios + "\n";
contenido = contenido + registro;
}
BufferedWriter wrtr = new BufferedWriter(new FileWriter(destFile, true));
wrtr.append(line + "\n");
wrtr.close();
line = null;
}
System.out.println("Data is added to the temporary");
w.append(contenido);
w.close();
br.close();
System.out.println("Successfully complete process");
} catch (Exception e) {
e.printStackTrace();
} finally {
sourceFile.delete();
}
}
}
I did an exercise treating the file with FileInputStream() and it worked and kept the value, and it is the following code:
private void testBinary(File filename) {
try {
FileInputStream FileOrigin = new FileInputStream(filename);
// Arrays
byte[] biyeFile = new byte[(int) filename.length()];
int[] intArray = new int[biyeFile.length];
char[] CharArrayBit = new char[intArray.length];
FileOrigin.read(biyeFile);
for (int i = 0; i < biyeFile.length; i++) {
// Converting each char into its byte equivalent
intArray[i] = (int) Byte.toUnsignedInt(biyeFile[i]);
}
File temp = new File("C:/MOVIMIENTO/ebcdic/ascii/", filename.getName() + ".TMP");
temp.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(temp);
for (int j = 0; j < charArrayBit.length; ++j) {
charArrayBit[j] = (char) intArray[j];
try {
if ((intArray[j] != 10) && (intArray[j] != 13)) {
fileOutputStream.write(charArrayBit[j]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
FileOrigin.close();
fileOutputStream.close();
filename.delete();
temp.renameTo(filename);
} catch (IOException e) {
e.printStackTrace();
}
}
But I can't seem to implement the logic I made with the one that is already there and I'm getting stuck :( on how I can deal line by line in bytes. Try this Java - Read line using InputStream
The mess I have is that by using String I already lose the value String data; data = br.readLine() String line = data;
Update:
The idea is that the temporary file where I am printing the TID and binary is as follows:
file dc.tmp
200232133:..3....¢...€ . ...
300232133:.....Þù...€ ....€
400232133:ù....Þù...€ ....€ ....
etc
This is some VB.net code that I'm basing on pulling out the binary:
While POS < inputFile.Length
While reg < rowlen
dato1 = inputFile.ReadByte()
POS = POS + 1
reg = reg + 1
dato11 = BitConverter.GetBytes(dato1)
If (binary = 1 And (reg > 589 And reg <= 589 + 53 + 53)) Then
' here you should read two bytes and convert it to one
byte1 = dato1
' now read the second byte
byte2 = inputFile.ReadByte()
reg = reg + 1
POS = POS + 1
final = CInt("&H" & (Chr(byte1) + Chr(byte2)))
Else
dato2 = Encoding.Convert(source, DEST, dato11)
final = dato2(0)
End If
Print(1, Chr(final))
If (reg < 7) Then 'the first positions give us the type of message
MTI = MTI + Chr(dato1)
End If
If reg = 7 Then
binary = 0
rowlen = 1400
If (MTI = "924007") Then ' binary
binary = 1
rowlen = 1400 + 53
End If
MTI = ""
End If
End While
POS = POS + 2
reg = 0
End While
Thank you.

Name the images that i get from a web site in Java

I am scraping a web site and as a last part, I get their product images to the folder. I want to name these images like (product_id + numberOfImages) I mean if product has a 2 images, there will be 2 png like (productId_1) (productId_2).
I have productId and also images there is no problem. I just want to know how to name it as I want. Here is my code.
for(Element imageElement : imageElements){
String strImageURL = imageElement.attr("src");
String strImageName =product_id + "_" + ??;
try {
URL urlImage = new URL(strImageURL);
InputStream in = urlImage.openStream();
byte[] buffer = new byte[4096];
int n = -1;
OutputStream os = new FileOutputStream( IMAGE_DESTINATION_FOLDER + "/" + strImageName );
while ( (n = in.read(buffer)) != -1 ){
os.write(buffer, 0, n);
}
//close the stream
os.close();
} catch (IOException e) {
System.out.println("sponsored product");
}
// for loop images
}
I assume you are asking what to write instead of the ?? in the code in your question. Just create a counter variable.
int counter = 0;
for(Element imageElement : imageElements){
String strImageURL = imageElement.attr("src");
String strImageName = product_id + "_" + (++counter);
try {
URL urlImage = new URL(strImageURL);
InputStream in = urlImage.openStream();
byte[] buffer = new byte[4096];
int n = -1;
OutputStream os = new FileOutputStream( IMAGE_DESTINATION_FOLDER + "/" + strImageName );
while ( (n = in.read(buffer)) != -1 ){
os.write(buffer, 0, n);
}
//close the stream
os.close();
} catch (IOException e) {
System.out.println("sponsored product");
}
// for loop images
}

Httpservletresponse - add multiple documents to it

Is there any way i can add multiple documents to a httpservletresponce.
This is the scenario.
I am looping through a list of filenames that a customer wants to print and retrieve them from an FTP location.
Now im able to add each one of the individually and show them in a browser. I want to show all of them..at a time.. in one browser.
Below is what i do to send one file to the browser.
is = ftp.retrieveFileStream(strFile);
ByteArrayOutputStream baos = convertTIFFtoPDF(is);
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-disposition",
"attachment;filename=\""
+ "importDocs.pdf" + "\"");
ServletOutputStream out = response
.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
How about concatenating all the pdf files in the server and deliver as one pdf file to the browser?
Adding more info due to request:
If you are on Linux, you could easily use gs or pdftk for this purpose. Windows ports should also be available.
You would use gs to concatenate pdf files like this:
gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf [...] lastfile.pdf
You would use pdftk to concatenate pdf files like this:
pdftk *.pdf cat output onelargepdfile.pdf
So here are the steps that I would follow provided that the server has gs or pdftk installed:
Access all the pdf files from the remote location (your FTP server) to a directory in your server where you are running the application. Make sure each pdf file has a unique name to avoid multiple requests overriding files.
Execute gs or pdftk using a system command execution facility (Runtime.exec) from the servlet. Make sure the command executed generates the concatenated pdf with a unique file name.
Send the generated concatenated pdf to the browser using code similar to what you are already using.
Clean the server directory.
Finally.. here we go
for (PdfBean pdfBean : list)
{
if(!pdfBean.getFileName().isEmpty()&&!pdfBean.getFileLocation().isEmpty()){
msgDH.InsertUserHistDtls(pdfBean.getHawb(), userId, pdfBean.getCustomer(), pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getDocType(), "Print");
msgDH.InsertLogDtls(pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getCustomer(), userId);
FTPClient ftp = new FTPClient();
int tiffPages = 0;
try
{
ftp.connect(ftpserver);
} catch (SocketException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
boolean login = ftp.login(ftpusername, ftppassword);
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
int reply;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
System.out.println("FTP server refused connection.");
} else
{
// ftp.enterLocalPassiveMode();
ftp.enterLocalActiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(pdfBean.getFileLocation());
/* FTPFile[] */
ftpFiles = ftp.listFiles();
/* FTPFile[] */// ftpFiles = ftp.listFiles();
// ftp.completePendingCommand();
}
String fileName = pdfBean.getFileLocation() + "/"
+ pdfBean.getFileName();
if ("/interface/oracle/dds/generic/hold/TIF"
.equalsIgnoreCase(pdfBean.getFileLocation()))
{
int i = 0;
String F = pdfBean.getFileName().replaceAll(".PDF",
".TIF");
// FTPFile[] ftpFiles =
// ftp.listFiles(pdfBean.getFileLocation());
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
if (i == 0)
{
F = pdfBean.getFileName().replaceAll(".PDF",
".TIFF");
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
}
int Repcode = ftp.getReplyCode();
//
// System.out.println(Repcode);
/* if(fileName.endsWith(".TIF")) */
InputStream is = (InputStream) ftp.retrieveFileStream(fileName);
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
// ftp.completePendingCommand();
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
ra1 = new RandomAccessFileOrArray(is);
tiffPages = TiffImage.getNumberOfPages(ra1);
System.out.println("No of pages in image is : "
+ tiffPages);
for (int a = 1; a <= tiffPages; a++)
{
try
{
Image img = TiffImage.getTiffImage(ra1, a);
if (img != null)
{
if (img.getScaledWidth() > 500
|| img.getScaledHeight() > 700)
{
img.scaleToFit(800, 800);
}
doc.setPageSize(new Rectangle(img
.getScaledWidth(), img
.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
// doc.
doc.newPage();
// ++pages;
}
} catch (Throwable e)
{
System.out.println("Exception " + " page "
+ (a + 1) + " " + e.getMessage());
}
}
is.close();
ra1.close();
}
else{
InputStream pdf = ftp.retrieveFileStream(fileName);
if(pdf != null) {
PdfReader pdfRea = new PdfReader(pdf);
readers.add(pdfRea);
totalPages += pdfRea.getNumberOfPages();
}
/*totalPages += pdfRea.getNumberOfPages();
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}*/
}
ftp.logout();
ftp.disconnect();
ftp = null;
}}
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}
}
doc.close();
write.flush();
write.close();
System.out.println("done printing");
}
FileInputStream fiss = new FileInputStream(temp);
bis = new BufferedInputStream(fiss);
response.reset();

Add pdf and tiff to the same pdf document and display it in the browser

I am using the below code to retrieve a file from an ftp server and display it in the browser.
boolean fileFormatType = fileName.endsWith(".PDF");
if (fileFormatType) {
if (FilePdf != null && FilePdf.length() > 0) {
is = ftp.retrieveFileStream(strFile);
bis = new BufferedInputStream(is);
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
"inline;filename=example.pdf");
ServletOutputStream outputStream = response
.getOutputStream();
System.out.println("here ");
byte[] buffer = new byte[1024];
int readCount;
while ((readCount = bis.read(buffer)) > 0){
outputStream.write(buffer, 0, readCount);
}
outputStream.flush();
outputStream.close();
}
} else {
is = ftp.retrieveFileStream(strFile);
ByteArrayOutputStream baos = convertTIFFtoPDF(is);
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-disposition",
"attachment;filename=\"" + "importDocs.pdf" + "\"");
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
But now, i need to add the multiple files in a folder (the folder could contain PDFs and TIFFs) and display them all at a time in a browser. I have been trying unsuccessfully for the past three days. I could post the code that i tried here but i want a fresh opinion/approach. Please help me solve this. I am using itextpdf5.1 commons-io.util apis
I get a negative array size exception btw.
This is the final answer to my problem.
for (PdfBean pdfBean : list)
{
if(!pdfBean.getFileName().isEmpty()&&!pdfBean.getFileLocation().isEmpty()){
msgDH.InsertUserHistDtls(pdfBean.getHawb(), userId, pdfBean.getCustomer(), pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getDocType(), "Print");
msgDH.InsertLogDtls(pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getCustomer(), userId);
FTPClient ftp = new FTPClient();
int tiffPages = 0;
try
{
ftp.connect(ftpserver);
} catch (SocketException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
boolean login = ftp.login(ftpusername, ftppassword);
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
int reply;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
System.out.println("FTP server refused connection.");
} else
{
// ftp.enterLocalPassiveMode();
ftp.enterLocalActiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(pdfBean.getFileLocation());
/* FTPFile[] */
ftpFiles = ftp.listFiles();
/* FTPFile[] */// ftpFiles = ftp.listFiles();
// ftp.completePendingCommand();
}
String fileName = pdfBean.getFileLocation() + "/"
+ pdfBean.getFileName();
if ("/interface/oracle/dds/generic/hold/TIF"
.equalsIgnoreCase(pdfBean.getFileLocation()))
{
int i = 0;
String F = pdfBean.getFileName().replaceAll(".PDF",
".TIF");
// FTPFile[] ftpFiles =
// ftp.listFiles(pdfBean.getFileLocation());
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
if (i == 0)
{
F = pdfBean.getFileName().replaceAll(".PDF",
".TIFF");
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
}
int Repcode = ftp.getReplyCode();
//
// System.out.println(Repcode);
/* if(fileName.endsWith(".TIF")) */
InputStream is = (InputStream) ftp.retrieveFileStream(fileName);
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
// ftp.completePendingCommand();
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
ra1 = new RandomAccessFileOrArray(is);
tiffPages = TiffImage.getNumberOfPages(ra1);
System.out.println("No of pages in image is : "
+ tiffPages);
for (int a = 1; a <= tiffPages; a++)
{
try
{
Image img = TiffImage.getTiffImage(ra1, a);
if (img != null)
{
if (img.getScaledWidth() > 500
|| img.getScaledHeight() > 700)
{
img.scaleToFit(800, 800);
}
doc.setPageSize(new Rectangle(img
.getScaledWidth(), img
.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
// doc.
doc.newPage();
// ++pages;
}
} catch (Throwable e)
{
System.out.println("Exception " + " page "
+ (a + 1) + " " + e.getMessage());
}
}
is.close();
ra1.close();
}
else{
InputStream pdf = ftp.retrieveFileStream(fileName);
if(pdf != null) {
PdfReader pdfRea = new PdfReader(pdf);
readers.add(pdfRea);
totalPages += pdfRea.getNumberOfPages();
}
/*totalPages += pdfRea.getNumberOfPages();
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}*/
}
ftp.logout();
ftp.disconnect();
ftp = null;
}}
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}
}
doc.close();
write.flush();
write.close();
System.out.println("done printing");
}
FileInputStream fiss = new FileInputStream(temp);
bis = new BufferedInputStream(fiss);
response.reset();

how to add ProgressMonitorInputStream to ftp upload?

Can anybody see what is wrong with this code. it does not show up progress-bar but uploades all the files.
I did checkout sun tutorial and swingworkers also but i couldn't fix it yet.
private static boolean putFile(String m_sLocalFile, FtpClient m_client) {
boolean success = false;
int BUFFER_SIZE = 10240;
if (m_sLocalFile.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(m_sLocalFile);
int size = (int) f.length();
System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(m_sLocalFile);
//test
InputStream inputStream = new BufferedInputStream(
new ProgressMonitorInputStream(null,"Uploading " + f.getName(),in));
//test
OutputStream out = m_client.put(f.getName());
int counter = 0;
while (true) {
int bytes = inputStream.read(buffer); //in
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
inputStream.close();
success =true;
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
return true;
}
I think your code is fine.
Maybe the task isn't taking long enough for the progress bar to be needed?
Here's a modified version of your code which reads from a local file and writes to another local file.
I have also added a delay to the write so that it gives the progress bar time to kick in.
This works fine on my system with a sample 12MB PDF file, and shows the progress bar.
If you have a smaller file then just increase the sleep from 5 milliseconds to 100 or something - you would need to experiment.
And I didn't even know that the ProgressMonitorInputStream class existed, so I've learnt something myself ;].
/**
* main
*/
public static void main(String[] args) {
try {
System.out.println("start");
final String inf = "d:/testfile.pdf";
final String outf = "d:/testfile.tmp.pdf";
final FileOutputStream out = new FileOutputStream(outf) {
#Override
public void write(byte[] b, int off, int len) throws IOException {
super.write(b, off, len);
try {
// We delay the write by a few millis to give the progress bar time to kick in
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
putFile(inf, out);
System.out.println("end");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static boolean putFile(String m_sLocalFile, OutputStream out /*FtpClient m_client*/) {
boolean success = false;
int BUFFER_SIZE = 10240;
if (m_sLocalFile.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(m_sLocalFile);
int size = (int) f.length();
System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(m_sLocalFile);
//test
InputStream inputStream = new BufferedInputStream(
new ProgressMonitorInputStream(null,"Uploading " + f.getName(),in));
//test
//OutputStream out = m_client.put(f.getName());
int counter = 0;
while (true) {
int bytes = inputStream.read(buffer); //in
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
inputStream.close();
success =true;
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
return true;
}

Categories