Java – add a title to an existing PDF file using pdfbox
I'm trying to add headers to an existing PDF file It works, but the headers in the existing PDF are messed up by font changes If I delete the set font, the title will not be displayed This is my code:
// the document PDDocument doc = null; try { doc = PDDocument.load( file ); List allPages = doc.getDocumentCatalog().getAllPages(); //PDFont font = PDType1Font.HELVETICA_BOLD; for( int i=0; i<allPages.size(); i++ ) { PDPage page = (PDPage)allPages.get( i ); PDRectangle pageSize = page.findMedia@R_657_2419@(); PDPageContentStream contentStream = new PDPageContentStream(doc,page,true,true); PDFont font = PDType1Font.TIMES_ROMAN; float fontSize = 15.0f; contentStream.beginText(); // set font and font size contentStream.setFont( font,fontSize); contentStream.moveTextPositionByAmount(700,1150); contentStream.drawString( message); contentStream.endText(); //contentStream. contentStream.close();} doc.save( outfile ); } finally { if( doc != null ) { doc.close(); } } }`
Solution
Basically, you are in the current version 1.8 Encountered in 2 PDF@R_657_2419 @Wrong
resolvent:
Before using fonts, add the getfonts call of page resources after creating a new content stream:
PDPage page = (PDPage)allPages.get( i ); PDRectangle pageSize = page.findMedia@R_657_2419@(); PDPageContentStream contentStream = new PDPageContentStream(doc,true); page.getResources().getFonts(); // <<<<<<<< PDFont font = PDType1Font.TIMES_ROMAN; float fontSize = 15.0f; contentStream.beginText();
Error itself:
Error in pdresources Addfont method, which is from pdpagecontentstream Of SetFont call:
public String addFont(PDFont font) { return addFont(font,MapUtil.getNextUniqueKey( fonts,"F" )); }
It uses the current contents of the fonts member variable to determine the unique name of the new font resource on the page at hand Unfortunately, this member variable can still (and in your case) be uninitialized at this time This results in maputil The call to getnextuniquekey (font, "F") always returns F0
Then implicitly initialize the font variable during a later addfont (pdfont, string) call
Therefore, if, unfortunately, a font named F0 already exists on the page, it will be replaced with a new font
After your PDF test, this is what happened in your case Because the existing font F0 uses some custom encoding and the replacement font uses standard fonts, the text originally written with F0 now looks like garbled code
The solution mentioned above implicitly initializes the member variable, thus preventing font replacement
If you plan to use it in production PDF@R_657_2419 @If you perform this task, you may need to report the error
PS: as mentioned in the comments above, there is another error to observe in the context of inheriting resources It should also cause PDF@R_657_2419 @Development concerns
PPS: the problem at hand is already PDF@R_657_2419 @For version 1.8 3 and 2.0 0 was repaired, see pdfbox-1753