This question already has answers here:
Problem with empty page when using Apache PDFBox to add image to PDF
(1 answer)
Edit pdf page using pdfbox
(3 answers)
Opening a content stream blanks saved content?
(2 answers)
PdfBox adding multiple images into pdf
(1 answer)
Table disappears when drawn before contentStream - PDFBox with Boxable
(1 answer)
Closed 4 years ago.
I want to highlight a perticular text in the pdf.I have writen the following code but i am getting empty pdf with the box.I want to show the existing pdf content and the box should be drawn on the text so it will act as a text highliter.
File file = new File(pdfName);
PDDocument document = PDDocument.load(file);
PDPage page = document.getPage(0);
//Instantiating the PDPageContentStream class
PDPageContentStream contentStream = new PDPageContentStream(document, page);
//Setting the non stroking color
contentStream.setNonStrokingColor(Color.DARK_GRAY);
//Drawing a rectangle
contentStream.addRect(data.get(0).getX(), data.get(0).getY(), data.get(0).getWidth(), data.get(0).getHeight());
//Drawing a rectangle
contentStream.fill();
System.out.println("rectangle added");
//Closing the ContentStream object
contentStream.close();
//Saving the document
//File file2 = new File("CompareOutput.pdf");
//File fileOutput = new File("CompareOutput.pdf");
document.save("CompareOutput.pdf");
//Closing the document
document.close();
Instead of
PDPageContentStream contentStream = new PDPageContentStream(document, page);
use
PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true))
This way your new content stream is appended.
However I expect another problem, you may want the "highlight" to be transparent. Have a look at this answer.
Related
This question already has answers here:
Table disappears when drawn before contentStream - PDFBox with Boxable
(1 answer)
PDFBox : PDPageContentStream's append mode misbehaving
(1 answer)
Cannot figure out how to use PDFBox
(2 answers)
Closed 3 years ago.
I'm trying to save an image into an existing pdf using apache PDFBOX,but my contents are getting deleted and i get blank document when I place the image on top of the pdf,Is there a solution to the problem?
My Code Looks like this.
public class TestPdfImage {
public static void main(String args[]) throws Exception {
//Loading an existing document
File file = new File("...../mydoc.pdf");
PDDocument doc = PDDocument.load(file);
//Retrieving the page
PDPage page = doc.getPage(0);
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("...../sample.png",doc);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page);
//Drawing the image in the PDF document
contents.drawImage(pdImage, 70, 250);
System.out.println("Image inserted");
//Closing the PDPageContentStream object
contents.close();
//Saving the document
doc.save(".../sample.pdf");
//Closing the document
doc.close();
}
}
Try to use the append-mode
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
Edit
TilmanHausherr mentioned
new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
Thats why
I am relativly new to Java and I want to replace an existing iText based Javascript with pdfbox. (Java 2.0)
I have a pdf-Formsheet (but this sheet has no Acroform entries) and I want to fill it with information (Name, Birthdate and so on). The pdf is in a rectangular special size (like a contact card).
My code so far:
File file = new File("ToBeFilled.pdf");
PDDocument document = PDDocument.load(file);
System.out.println("PDF loaded");
//Retrieving the page
PDPage page = (PDPage)document.getPages().get( 0 );
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream content = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
content.beginText();
//Setting the font to the Content stream
content.setFont(font, 30);
//Setting the position for the line (float x, float y), (0,0) = lower left corner
content.newLineAtOffset(100, 400);
String text = "This is the sample document and we are adding content to it.";
String text1 = "This is an example of adding text to a page in the pdf document. we can add as many lines";
String text2 = "as we want like this using the ShowText() method of the ContentStream class";
//Adding text in the form of string
content.showText(text);
//Adding text in the form of string
content.newLine();
content.showText(text1);
content.newLine();
content.showText(text2);
//Ending the content stream
content.endText();
System.out.println("Text added");
content.close();
//Saving the document
document.save("newPrint.pdf");
//Closing the document
document.close();
The text does not show. What am I missing here? I thought with the correct text-positions I could simply write on the pdf?
The source is working.
Maybe your content.newLineAtOffset(100, 400); is too huge - out of bounds - for your little card.
By the way, you have to setLeading(float) to use newLine() meaningfuly.
I am using PdfBox to generate pdf with an existing Pdf containing the template which has to be used for every Pdf that i want to generate.
But When i try to load the template pdf and wants to write something in it, all previous contains were removed.
So i want both the content should be shown.
Please suggest any solution for it.
Here is the code i am trying to do :
//Loading an existing document
File file = new File("/home/spaneos/ScoringReports-TM-110617.pdf");
PDDocument document = PDDocument.load(file);
//Retrieving the pages of the document
PDPage page = document.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
//Setting the leading
contentStream.setLeading(14.5f);
//Setting the position for the line
contentStream.newLineAtOffset(25, 725);
String text1 = "This is an example of adding text to a page in the pdf document.we can add as many lines";
String text2 = "as we want like this using the ShowText() method of the ContentStream class";
//Adding text in the form of string
contentStream.showText(text1);
contentStream.newLine();
contentStream.showText(text2);
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("/home/spaneos/Downloads/man-161282_960_720.png",document);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(document, page);
contentStream.endText();
System.out.println("Content added");
//Closing the PDPageContentStream object
contents.close();
//Closing the content stream
contentStream.close();
//Saving the document
document.save(System.getProperty("user.dir").concat("/PdfBox_Examples/sample.pdf"));
//Closing the document
document.close();
You create the PDPageContentStream instances like this
PDPageContentStream contentStream = new PDPageContentStream(document, page);
[...]
PDPageContentStream contents = new PDPageContentStream(document, page);
Creating it using this constructor replaces any existing content streams with the new one. Instead use this one:
PDPageContentStream contents = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);
AppendMode.APPEND here tells PDFBox to append the new stream, the first true tells it to compress the stream, and the second true tells it to reset the graphics state at the start of your added stream.
Furthermore, you don't really use the second content stream...
I am not getting any tutorial for adding a text watermark in a PDF file? Can you all please guide me, I am very new to PDFBOX.
Its not duplicate, the link in the comment didn't help me. I want to add text, not an image to the pdf.
Here is an example using PDFBox 2.0.2. This will load a PDF and write some text in the bottom right corner in a red transparent font. If it is a multiple page PDF the watermark will appear on every page. It might not be production ready, as I am not sure if there are some additional null conditions that need to be checked, but it should get you running in the right direction.
Keep in mind that this particular block of code will not modify the original PDF, but will create a new PDF using the Tmp_(filename) as the output.
private static void watermarkPDF (File fileStored) {
File tmpPDF;
PDDocument doc;
tmpPDF = new File(fileStored.getParent() + System.getProperty("file.separator") +"Tmp_"+fileStored.getName());
doc = PDDocument.load(fileStored);
for(PDPage page:doc.getPages()){
PDPageContentStream cs = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
String ts = "Some sample text";
PDFont font = PDType1Font.HELVETICA_BOLD;
float fontSize = 14.0f;
PDResources resources = page.getResources();
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
r0.setNonStrokingAlphaConstant(0.5f);
cs.setGraphicsStateParameters(r0);
cs.setNonStrokingColor(255,0,0);//Red
cs.beginText();
cs.setFont(font, fontSize);
cs.setTextMatrix(Matrix.getTranslateInstance(0f,0f));
cs.showText(ts);
cs.endText();
}
cs.close();
}
doc.save(tmpPDF);
}
I am attempting to create a PDF report from a Java ResultSet. If the report was only one page, I would have no problem here. The issue comes from the fact that the report could be anywhere from one to ten pages long. Right now, I have this to create a single-page document:
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_LETTER);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document,page);
So my question is, how do I create pages dynamically as they are needed. Is there an object-oriented answer staring me in the face and I just cannot see it?
As I expected, the answer was staring me right in the face, I just needed someone to point it out for me.
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_LETTER);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document,page);
//generate data for first page
content.close();
//if number of results exceeds what can fit on the first page
page = new PDPage(PDPage.PAGE_SIZE_LETTER);
document.addPage(page);
content = new PDPageContentStream(document,page);
//generate data for second page
content.close();
Thanks to #mkl for the answer.
To Create Multi Page PDF Document using PDFBox:
(a) Create new page, new content stream, Move to Top Left, start writing. While writing each word check whether space required is not crossing mediabox width. If crosses, move to next line leftmost and start writing. Continue writing till the last line of the page.
(b) Close the contentStream and add the current page to the document when the writing operation reaches the last line of the current page,
(c) Repeat steps (a) and (b) till the last record/row/line is written.
PDDocument document = new PDDocument();
PDFont font = PDType1Font.HELVETICA;
//For Each Page:
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.setFont(font, 12);
contentStream.beginText();
contentStream.moveTextPositionByAmount(100, 700);
contentStream.drawString("PDF BOX TEXT CONTENT");
contentStream.endText();
contentStream.close();
document.addPage(page);
//After All Content is written:
document.save(pdfFile);
document.close();
Hint: Use Font parameters like size/height and remaining media box height to determine the last line of the page.