[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 354
  • Last Modified:

Can an expert review my code that uses iText.


Hi,
   I've written some java code that uses iText.  Is there an expert here willing to look at my code and make suggestions? Pasted below is an ftp site where all related files can be downloaded.

Below that are calls to methods I wrote, following that is the class.

Thanks for any suggestions,
El

ftp to ...
joneset1231.web.aplus.net

user - joneset
password - guest1

download files -

createPdf.jar  
dothis3.java - file to test class
sales2.pdf   - pdf template file (contains fields)

iText.jar   - if needed
runthem.bat - a little dos batch file that might help

----------------------------------
package createPdf;
/*      Using the iText class, this code reads a template pdf (sales2.pdf) and
      populates the form fields with values from a hashmap.  The result is held
      in a temparary buffer until the page is complete and then the page is
      written to an output file (out2.pdf).
*/

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.util.HashMap;
import java.util.Iterator;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;


public class pdfFieldAndFileMerge {

      private String inPdf;
      private String outPdf;

      private PdfReader sourcePdf;
      private PdfReader pdfSourceToDest;

      private PdfWriter writepdf1;
      private PdfWriter writepdf3;
      private PdfWriter writepdf5;

      private AcroFields form;

      private PdfStamper stampbytestream;

      private FileOutputStream outfilestream;
      private FileOutputStream outfilestream5;

      private ByteArrayOutputStream outbytestream1;
      private ByteArrayOutputStream outbytestream2;
      private ByteArrayOutputStream outbytestream3;

      private int numpdfpages5;

      private PdfImportedPage page;
      private PdfImportedPage page_tmp5;

      private PdfContentByte contentbytes;
      private PdfContentByte contentbytes5;


      private Document document;
      private Document document_tmp;
      private Document document_tmp5;


      public pdfFieldAndFileMerge (String inPdf,String outPdf) {
            
                  setInPdf(inPdf);
                  setOutPdf(outPdf);
      }

      private void setInPdf (String pdfIn) { inPdf = pdfIn; }  

      public String getInPdf () { return inPdf; }  

      private void setOutPdf (String pdfOut) { outPdf = pdfOut; }
 
      public String getOutPdf () { return outPdf; }  

      public void createBuffCopySourcePdf () {
            
                try {      // Keep a buffered copy of template pdf in outbytestream3.
                  // Outbytestream3 will be copied to outbytestream1. Pdf form will
                  // be read and written in outbytestream1.
                  // This method needs to be run only one time per instance.

                  outbytestream3 = new ByteArrayOutputStream();
                  PdfReader sourcePdf_tmp3 = new PdfReader(getInPdf());
                  Document document_tmp3 = new Document(sourcePdf_tmp3.getPageSizeWithRotation(1));

                  PdfCopy writepdf1 = new PdfCopy(document_tmp3, outbytestream3);
                  document_tmp3.open();

                  int numpdfpages_tmp3 = sourcePdf_tmp3.getNumberOfPages();
                         PdfImportedPage page_tmp3;

                          for (int i = 0; i < numpdfpages_tmp3; ) {
                       
                              page_tmp3 = writepdf1.getImportedPage(sourcePdf_tmp3, ++i);
                              writepdf1.addPage(page_tmp3);
                  }
                  
                  PRAcroForm form_tmp3 = sourcePdf_tmp3.getAcroForm();

                  if (form_tmp3 != null)
                        writepdf1.copyAcroForm(sourcePdf_tmp3);
                  document_tmp3.close();

            } catch (Exception e) {      e.printStackTrace(); }
      }

      public void getBuffCopySourcePdf () {
            
                try {      // This method retreives a blank copy of the template pdf to sourcePdf.
                  // Then it copies the buffered blank source pdf form from outbytestream3 to
                  // outbytestream1 so that outbytestream1 can be updated by the stamper.      

                  sourcePdf = new PdfReader(outbytestream3.toByteArray());
                  outbytestream1 = new ByteArrayOutputStream();
                  outbytestream3.writeTo(outbytestream1);
                  
            } catch (Exception e) {      e.printStackTrace(); }
      }


      public void newPdfOutputBuf () {
            
                try {      // Setup to buffer the output pdf stream.  Outbytestream2 can
                  // become pretty large.

                  
                  outbytestream2 = new ByteArrayOutputStream();
                  

            } catch (Exception e) {      e.printStackTrace(); }
      }

      public void appendDestToOutPdfStream () {

            try {      // Preappend outbytestream2 with contents of destination pdf file (if the
                  // destination pdf is not empty and should be appended to.
            
                  PdfReader sourcePdf_tmp = new PdfReader(getOutPdf());
                  document_tmp = new Document();
                  writepdf3 = PdfWriter.getInstance(document_tmp, outbytestream2);
                  document_tmp.open();

                  PRAcroForm form_tmp;
                  PdfImportedPage page_tmp;
                  contentbytes = writepdf3.getDirectContent();
                  int numpdfpages_tmp3 = sourcePdf_tmp.getNumberOfPages();

                  for (int cnt = 0; cnt < numpdfpages_tmp3; )
                  {
                        document_tmp.newPage();
                        page_tmp = writepdf3.getImportedPage(sourcePdf_tmp, ++cnt);
                        contentbytes.addTemplate(page_tmp,0,0);
                  }

                  document_tmp.newPage();
                  writepdf3.flush();
                  writepdf3.pause();

            } catch (Exception e) {      e.printStackTrace(); }
      }



      public void writeByteStream2ToOutPdf () {

            try { // Write bytestream2 to output pdf.
                  
                  if ((document_tmp != null) && document_tmp.isOpen())
                         document_tmp.close();
                  outfilestream = new FileOutputStream(getOutPdf());
                  /* outbufferedfilestream = new BufferedOutputStream(outfilestream);*/
                  /* outbytestream2.writeTo(outbufferedfilestream); */
                  outbytestream2.writeTo(outfilestream);

            } catch (Exception e) {      e.printStackTrace(); }
      }

      public void writeByteStream1ToOutPdf () { // Write bytestream1 to output pdf.

            try {
                  /* outfilestream5 = new BufferedOutputStream( new FileOutputStream(getOutPdf())); */

                   outfilestream5 = new FileOutputStream(getOutPdf());

                  pdfSourceToDest = new PdfReader(outbytestream1.toByteArray());
                  numpdfpages5 = pdfSourceToDest.getNumberOfPages();

                  document_tmp5 = new Document();
                  writepdf5 = PdfWriter.getInstance(document_tmp5, outfilestream5);
                  document_tmp5.open();

                  contentbytes5 = writepdf5.getDirectContent();
                  numpdfpages5 = pdfSourceToDest.getNumberOfPages();

                  for (int cnt = 0; cnt < numpdfpages5; )
                  {
                        document_tmp5.newPage();
                        page_tmp5 = writepdf5.getImportedPage(pdfSourceToDest, ++cnt);
                        contentbytes5.addTemplate(page_tmp5,0,0);
                  }
                  document_tmp5.newPage();
                  writepdf5.flush();
                  writepdf5.pause();
                  

            } catch (Exception e) {      e.printStackTrace(); }
      }
      
      public void appendByteStream1ToOutPdf () { // Append bytestream1 to output pdf.

            try {

                  pdfSourceToDest = new PdfReader(outbytestream1.toByteArray());
                  numpdfpages5 = pdfSourceToDest.getNumberOfPages();

                  contentbytes5 = writepdf5.getDirectContent();
                  numpdfpages5 = pdfSourceToDest.getNumberOfPages();

                  for (int cnt = 0; cnt < numpdfpages5; )
                  {
                        document_tmp5.newPage();
                        page_tmp5 = writepdf5.getImportedPage(pdfSourceToDest, ++cnt);
                        contentbytes5.addTemplate(page_tmp5,0,0);
                  }
                  document_tmp5.newPage();
                  writepdf5.flush();
                  writepdf5.pause();

            } catch (Exception e) {      e.printStackTrace(); }
      }


      public void closeByteStream1ToOutPdf () {

            try {
                  writepdf5.resume();

                  document_tmp5.newPage();
                  document_tmp5.close();

            } catch (Exception e) {      e.printStackTrace(); }
      }

      public void closewritePdf3 () {

            try {
                  writepdf3.resume();
                  writepdf3.close();
                  outfilestream.close();

            } catch (Exception e) {      e.printStackTrace(); }
      }


      public void resetnewPdfSourceBuf () {
            
                try {      // output bytesteam will get acroform fields merged with blank pdf

                  stampbytestream = new PdfStamper(sourcePdf, outbytestream1);
                  form = stampbytestream.getAcroFields();
                  
            } catch (Exception e) {      e.printStackTrace(); }
      }  


      public void mergeHashAndForm (HashMap mapForOutput) {

            try {

                  for (Iterator it = mapForOutput.entrySet().iterator(); it.hasNext();) {
                        java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
                        /*  System.out.println("pairs = " + entry.getKey() + "," + entry.getValue()); */
                        form.setField(entry.getKey().toString(), entry.getValue().toString());
                  }

            } catch (Exception e) {      e.printStackTrace(); }
      }


      public void closeTheStreamForFormWrite () {

            try {
                  stampbytestream.setFormFlattening(true);
                  stampbytestream.close();

            } catch (Exception e) {      e.printStackTrace(); }
      }

      public void writeByteStreamToOutPdfStream () {
            
            try {
                  
                  PdfReader pdfSourceToDest1 = new PdfReader(outbytestream1.toByteArray());
                  int numpdfpages_tmp3 = pdfSourceToDest1.getNumberOfPages();

                  writepdf3.resume();

                  for (int cnt = 0; cnt < numpdfpages_tmp3; )
                  {
                        document_tmp.newPage();
                        page = writepdf3.getImportedPage(pdfSourceToDest1, ++cnt);
                        contentbytes.addTemplate(page, 0, 0);
                  }
                  writepdf3.pause();

            } catch (Exception e) {      e.printStackTrace(); }
      }


}



----------------------------------------------


import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.util.ArrayList;
import java.util.HashMap;        
import java.util.Iterator;
import java.lang.Integer;  
import java.util.Calendar;
import java.util.GregorianCalendar;
import createPdf.*;


public class dothis3 {
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

      Calendar cal;
      int count = 1;

       try {

            cal = new GregorianCalendar();
            String start_time = "date = "+ cal.get(Calendar.DAY_OF_MONTH)+ " " + (cal.get(Calendar.MONTH)+1)+ " " +
                         cal.get(Calendar.YEAR) +" "+cal.get(Calendar.HOUR) +":"+ cal.get(Calendar.MINUTE) +":"+ cal.get(Calendar.SECOND);
            System.out.println("start_time = "+start_time);
            
            pdfFieldAndFileMerge tmpDoThis = new pdfFieldAndFileMerge("sales2.pdf","out2.pdf");            
            tmpDoThis.createBuffCopySourcePdf();


            theHashMap tmpHashMap = new theHashMap(count);
            System.out.println("count = "+count);
            
                  tmpDoThis.getBuffCopySourcePdf();
                  tmpDoThis.resetnewPdfSourceBuf();
                  tmpDoThis.mergeHashAndForm(tmpHashMap.getHashMap());      
                  tmpDoThis.closeTheStreamForFormWrite();            
                  tmpDoThis.writeByteStream1ToOutPdf();      

            cal = new GregorianCalendar();
            System.out.println("date = "+ cal.get(Calendar.DAY_OF_MONTH)+ " " + (cal.get(Calendar.MONTH)+1)+ " " +
                         cal.get(Calendar.YEAR) +" "+cal.get(Calendar.HOUR) +":"+ cal.get(Calendar.MINUTE) +":"+ cal.get(Calendar.SECOND) );


                  for (count = 2; count < 20; count++ ) {
                        if ( (count % 100) == 0 )
                              System.out.println("count = "+count);
                        tmpDoThis.getBuffCopySourcePdf();
                        tmpDoThis.resetnewPdfSourceBuf();
                        tmpDoThis.mergeHashAndForm(tmpHashMap.getHashMap());      
                        tmpDoThis.closeTheStreamForFormWrite();      
                        tmpDoThis.appendByteStream1ToOutPdf();
                  }
 
                  tmpDoThis.closeByteStream1ToOutPdf();

            cal = new GregorianCalendar();
            System.out.println("date = "+ cal.get(Calendar.DAY_OF_MONTH)+ " " + (cal.get(Calendar.MONTH)+1)+ " " +
                         cal.get(Calendar.YEAR) +" "+cal.get(Calendar.HOUR) +":"+ cal.get(Calendar.MINUTE) +":"+ cal.get(Calendar.SECOND) );


      } catch (Exception e) {      e.printStackTrace(); }
    }
}  
0
joneset
Asked:
joneset
  • 2
  • 2
1 Solution
 
TimYatesCommented:
what's the exact problem?

you want us just to read your code?
0
 
jonesetAuthor Commented:
Yes and give me some feedback to write better code.
0
 
jonesetAuthor Commented:
Mod,
Was hoping to get some suggestions to improve this java code that uses the iText class.  Did not get any.  Performance was pretty bad.  Took 15 + minutes on PC (and java -Xmx1024m) to get 3000 pages with 80+ pdf form fields (with labels) written to file.

Got required performance from iText when I abandon the stamper class and went with pasting text over flattened template pdf file.  Did use pdf template file to read in locations where text should be written on output page. This process was much faster and the resulting file was a much smaller file.  

To reiterate -
Stamper is great if output pdf needs to be read at a later time and the data in output pdf retrieved in a programatic sort of way.

Otherwise, very fast way to create pdf is with pdfContentByte (as in iText example FillBlanks.java).

So, although I might not have better code, I have what I need... which is better performance.
Please close this question and refund points.  Thanks
El
0
 
TimYatesCommented:
>> Please close this question and refund points.  Thanks

You will need to ask in Community Support:

http://www.experts-exchange.com/Community_Support/
0
 
moduloCommented:
PAQed with points refunded (500)

modulo
Community Support Moderator
0

Featured Post

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now