PdfWriter and Events

I want to create a PdfWriter object and set events for the header and footer. The problem is that I am creating a new PDF file. But my problem is that I already have a PDF file in the 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: document has no pages.

There are no exceptions without comments, but it does not add headers and footers. Any hints are much appreciated.

Regards, Tina

enter code here
+3
source share
1 answer

Yes.

You are trying to modify an existing PDF with PdfWriterwhen you should use PdfStamper.

, PdfWriter Document.

ColumnText PdfContentByte, myStamper.getOverContent(pageNum).

//etc ColumnText PdfContentByte ( ) .

PDF ( ), PdfStamper PdfImportedPage . PDF , - , ( ) . , PDF ( ByteArrayOutputStream , ), , .

, ColumnText.

PdfContentByte, PdfPageEvent, .

+3

Source: https://habr.com/ru/post/1772505/


All Articles