2

Hello Everyone I know this could be a simple problem I am facing but I am stuck on this for a while now. I am new in using itext. Basically I am working on a small project where I am trying to use to existing pdf to fill in the data from the database. But before I do that I just wanted to make sure if I can copy the data from database to already present pdf using itext. But I encountered this problem "cannot convert from void to pdf writer" I tried looking in itext mailing list and tried getting some sample code but could not anything helpful so I am here asking for help. Kindly help me out in my problem and give a rough idea of how to get data from databse and fill in the form.

for example form has a last name which is left blank so I need to pull the last name from database and put in the place of last name in the pdf. following is my code.

/**
 * 
 */

package itext.sample;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//import com.itextpdf.text.BaseColor;
//import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
//import com.itextpdf.text.Font;
//import com.itextpdf.text.Font.FontFamily;
//import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
//import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.DocWriter;

/**
 * @author prithvi
 *
 */
public class FirstPdf {

    private static final String Result = "D:/Eclipse Java/image.pdf";

    public static String main(String[] args) throws SQLException,IOException,DocumentException {
        try {

            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            System.out.println("Where is your MySQL JDBC Driver?");
            e.printStackTrace();
            return null;

        }
      System.out.println("MySQL JDBC Driver Registered!");
        Connection connection = null;
        try {
            connection = DriverManager
                    .getConnection("jdbc:mysql://69.167.139.172/bluedb",
                            "color", "prithvi");

        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return null;
        }

        if (connection != null) {
            System.out.println("You made it, take control your database now!");
        } else {
            System.out.println("Failed to make connection!");
        }
        // creating pdf document
    Document document = new Document();
    try {
          //writing to the outputfile
            PdfWriter writer= PdfWriter.getInstance(document,new FileOutputStream(Result)) .setInitialLeading(16);
            document.open(); //opening the document to do the action
            Statement stm = null;
            stm = connection.createStatement();//creating database query
            ResultSet rs = null;
            rs = stm.executeQuery("SELECT * FROM Sec1");
            PdfPTable table = new PdfPTable(2);
            PdfReader reader =new PdfReader ("D:/Eclipse Java/HiltonForms2014_r.pdf");
            AcroFields form = reader.getAcroFields();
            form.setField("LASTNAME", rs.getCursorName());
            int n = reader.getNumberOfPages();
            PdfImportedPage page;
            for( int i= 1; i <=n;i++)
            {
                page = writer.getImportedPage(reader,i);
                table.addCell(Image.getInstance(page));
            }
            document.add(table);
            document.close();
            connection.close();
            reader.close();


            /*while (rs.next()){

                        document.add(new Chunk(rs.getString(Result)));
                        document.add(new Chunk(""));
                        Font font = new Font(FontFamily.TIMES_ROMAN, 10,Font.BOLD, BaseColor.WHITE);
                        Chunk id = null;
                        id = new Chunk(rs.getString("Sec1ID"), font);
                        id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f , 1.5f);
                        id.setTextRise(6);
                        document.add(id);
                        document.add(Chunk.NEWLINE);
                        document.add(new Paragraph("hey there! you created a new pdf"));
                        stm.close();
                        connection.close();
                        document.close();
                    }*/



    }

                 catch (DocumentException | SQLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }


}
bumbble bee
  • 35
  • 2
  • 9

2 Answers2

1

I'm sorry, but your code is all wrong.

When you want to fill out a form, you need to use PdfStamper. See for instance: How to fill out a pdf file programatically?

In your case, the code would be:

PdfReader reader = new PdfReader("D:/Eclipse Java/HiltonForms2014_r.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(Result));
AcroFields form = stamper.getAcroFields();
form.setField("LASTNAME", rs.getCursorName());
stamper.setFormFlattening(true);
stamper.close();
reader.close();

These are some issues I've detected in your code:

Issue #1:

PdfReader reader =new PdfReader ("D:/Eclipse Java/HiltonForms2014_r.pdf");
AcroFields form = reader.getAcroFields();
form.setField("LASTNAME", rs.getCursorName());

You can indeed create an AcroFields instance from PdfReader, but in this case, the fields will be read-only, meaning that the setField() method won't do anything. Only an AcroFields instance obtained from a PdfStamper can be used to set fields.

Issue #2:

You want to fill out fields, which are interactive features, but you are using writer.getImportedPage(reader,i) where writer is an instance of PdfWriter. This means that you're throwing away all interactive features...

Issue #3:

I assume that you want to 2-up the filled out document. You are creating a table with 2 columns and you are adding the pages of an existing document as cells to this table, but:

  • you are creating a document with size A4 in portrait orientation. This will look awkward.
  • iText doesn't render incomplete rows, so if your existing PDF only has one page, the table won't be rendered. If the existing PDF has an odd number of pages, the last page will go missing.
  • The default width percentage of a PdfPTable is 80%. Add the margins of half an inch each, and you will end up with plenty of white space to the left and the right of your imported pages.

I think you should fill out the form using the above code in a first go, and then N-up the document in a second go.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
1

PdfWriter.getInstance(document, new FileOutputStream(Result).setInitialLeading(16); is a void.

So you have to change to:

PdfWriter writer= PdfWriter.getInstance(document,new FileOutputStream(Result)) 
writer.setInitialLeading(16);
Jens
  • 67,715
  • 15
  • 98
  • 113
  • That's indeed the cause of the exception (hence the up-vote), but overall, the code is wrong. There is no way the code snippet can work because `PdfReader.getAcroFields()` returns the fields in read-only mode. Moreover, the method `setInitialLeading(16)` doesn't make any sense in the context of this example. – Bruno Lowagie Aug 12 '15 at 07:32