Adding text to existing pdf which is closed using

2020-07-17 06:21发布

问题:

Hi I am creating PDF using itextsharp. Now my requirement is to add more text to the existing pdf. Is it possible if so then how can I do that?

Thanks Dipa

回答1:

Yes, with certain limitations.

It is difficult, but not impossible, to determine what is already on an existing page.

If all you want to do is add "page X of Y" to the bottom left corner of all your pages, that's easy.

PdfReader reader = new PdfReader( inPath );
PdfStamper stamper = new PdfStamper( reader, new FileOutputStream( outPath ) );
BaseFont font = BaseFont.createFont(); // Helvetica, WinAnsiEncoding
for (int i = 0; i < reader.getNumberOfPages(); ++i) {
  PdfContentByte overContent = stamper.getOverContent( i + 1 );
  overContent.saveState();
  overContent.beginText();
  overContent.setFontAndSize( font, 10.0f );
  overContent.setTextMatrix( xLoc, yLoc );
  overContent.showText( "Page " + (i + 1) + " of " + reader.getNumberOfPages() );
  overContent.endText();
  overContent.restoreState();
}
stamper.close();

A big watermark isn't much more difficult. Adding things to a PDF at one or more predetermined locations is quite doable.

At the other end of the spectrum is "change text within existing paragraphs and reflow them". That's all but impossible. It would be much easier to rebuild the original PDF with the new data.

In fact, if at all possible, just rebuild them. You did it once, do it again.