Tina Agrawal
Tina Agrawal

Reputation: 616

PdfWriter and Events

I want to create a PdfWriter Object and set Events for Header and Footer. The problem is it works if I create a new PDF. But my problem is I already have a PDF in Output Stream. Please find my sample code below.

Document document = new Document();
    try {
        // step 2:
        FileInputStream is = new FileInputStream("D://2.pdf");
        int nRead;
        byte[] data = new byte[16384];
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        while ((nRead = is.read(data, 0, data.length)) != -1) {
          buffer.write(data, 0, nRead);           
        }

        buffer.flush();
        PdfWriter writer = PdfWriter.getInstance(document,buffer);
        writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft);
        writer.setPageEvent(new DossierPortalUtil());

        document.setMargins(36, 36, 54, 72);
        // step 3:
        document.open();

        document.add( new Chunk("testing")); 

    } catch (Exception de) {
        de.printStackTrace();
    } 
    finally{
        document.close();
    }

If I comment the line

document.add( new Chunk("testing"));

I get an exception

Exception in thread "main" ExceptionConverter: java.io.IOException: The document has no pages.

Without commenting there are no exceptions but it doesnt add the Header and Footer. Any clues are highly appreciated.

Regards, Tina

enter code here

Upvotes: 3

Views: 4419

Answers (1)

Mark Storer
Mark Storer

Reputation: 15868

Yep.

You're trying to modify an existing PDF with PdfWriter, when you should be using PdfStamper.

Adding text with a stamper is Far Less Trivial than doing so with PdfWriter and a Document.

You need to create a ColumnText object, and get a PdfContentByte by calling myStamper.getOverContent(pageNum).

You add the paragraphs/chunks/etc to the ColumnText, and pass it the PdfContentByte (and some positional parameters) to draw the text.

Alternatively, you can create a separate PDF with your text (and anything else), then use PdfStamper & PdfImportedPage to import those pages and write them over top of the existing ones. PDF page backgrounds are transparent until you draw something over them, so the text (and stuff) will appear over top of the existing page. This is noticeably less efficient, as the second document has to be converted to a byte array in PDF syntax (if you're using a ByteArrayOutputStream instead of writing to a file, which would be even slower), parsed again, and then added to the original doc and written out a second time.

It's worth a little extra effort to use ColumnText.

You'll also need to write your header and footer directly with PdfContentByte calls, but you have to do that already within your PdfPageEvent, so those changes should be quite simple.

Upvotes: 3

Related Questions