What I am trying to do here is to create text and place it onto a blank page. That page would then be overlayed onto another document and that would then be saved as one document. In 1.8 I was able to create a blank PDPage in a PDF, write text to it as needed, then overlay that PDF with another and then save or view on screen using the code below -
overlayDoc = new PDDocument();
page = new PDPage();
overlayDoc.addPage(page);
overlayObj = new Overlay();
font = PDType1Font.COURIER_OBLIQUE;
try {
contentStream = new PDPageContentStream(overlayDoc, page);
contentStream.setFont(font, 10);
}
catch (Exception e){
System.out.println("content stream failed");
}
After I created the stream, when I needed to write something to the overlay document's contentStream, I would call this method, give it my x, y coords and tell it what text to write (again, this is in my 1.8 version):
protected void writeString(int x, int y, String text) {
if (text == null) return;
try {
contentStream.moveTo(x, y);
contentStream.beginText();
contentStream.drawString(text); // deprecated. Use showText(String text)
contentStream.endText();
}
catch (Exception e){
System.out.println(text + " failed. " + e.toString());
}
}
I would call this method whenever I needed to add text and to wherever I needed to do so. After this, I would close my content stream and then merge the documents together as such:
import org.apache.pdfbox.Overlay;
Overlay overlayObj = new Overlay();
....
PDDocument finalDoc = overlayObj.overlay(overlayDoc, originalDoc);
finalDoc now contains a PDDocument which is my original PDF with text overlayed where needed. I could save it and view it as a BufferedImage on the desktop. The reason I moved to 2.0 was that first off I needed to stay on top of the most recent library and also that I was having issues putting an image onto the page (see here).
The issue I am having in this question is that 2.0 no longer has something similar to the org.apache.pdfbox.Overlay class. To confuse me even more is that there are two Overlay classes in 1.8 (org.apache.pdfbox.Overlay and org.apache.pdfbox.util.Overlay) whereas in 2.0 there is only one. The class I need (org.apache.pdfbox.Overlay), or the methods it offers at least, are not present in 2.0 as far as I can tell. I can only find org.apache.pdfbox.multipdf.Overlay.
Here's some quick code that works, it adds "deprecated" over a document and saves it elsewhere:
PDDocument overlayDoc = new PDDocument();
PDPage page = new PDPage();
overlayDoc.addPage(page);
Overlay overlayObj = new Overlay();
PDFont font = PDType1Font.COURIER_OBLIQUE;
PDPageContentStream contentStream = new PDPageContentStream(overlayDoc, page);
contentStream.setFont(font, 50);
contentStream.setNonStrokingColor(0);
contentStream.beginText();
contentStream.moveTextPositionByAmount(200, 200);
contentStream.drawString("deprecated"); // deprecated. Use showText(String text)
contentStream.endText();
contentStream.close();
PDDocument originalDoc = PDDocument.load(new File("...inputfile.pdf"));
overlayObj.setOverlayPosition(Overlay.Position.FOREGROUND);
overlayObj.setInputPDF(originalDoc);
overlayObj.setAllPagesOverlayPDF(overlayDoc);
Map<Integer, String> ovmap = new HashMap<Integer, String>(); // empty map is a dummy
overlayObj.setOutputFile("... result-with-overlay.pdf");
overlayObj.overlay(ovmap);
overlayDoc.close();
originalDoc.close();
What I did additionally to your version:
declare variables
close the content stream
set a color
set to foreground
set a text position (not a stroke path position)
add an empty map
And of course, I read the OverlayPDF source code, it shows more possibilities what you can do with the class.
Bonus content:
Do the same without using the Overlay class, which allows further manipulation of the document before saving it.
PDFont font = PDType1Font.COURIER_OBLIQUE;
PDDocument originalDoc = PDDocument.load(new File("...inputfile.pdf"));
PDPage page1 = originalDoc.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(originalDoc, page1, true, true, true);
contentStream.setFont(font, 50);
contentStream.setNonStrokingColor(0);
contentStream.beginText();
contentStream.moveTextPositionByAmount(200, 200);
contentStream.drawString("deprecated"); // deprecated. Use showText(String text)
contentStream.endText();
contentStream.close();
originalDoc.save("....result2.pdf");
originalDoc.close();
Related
Yes, it seems a weird question, but I was not able to render a colored text in PDFBox.
Usually the code for generating text looks like that:
//create some document and page...
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
//defined some font
PDFont helveticaRegular = PDType1Font.HELVETICA;
//content stream for writing the text
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(helveticaRegular, 16);
contentStream.setStrokingColor(1f,0.5f,0.2f);
contentStream.newLineAtOffset(64, page.getMediaBox().getUpperRightY() - 64);
contentStream.showText("The hopefully colored text");
contentStream.endText();
//closing the stream
contentStream.close();
[...] //code for saving and closing the document. Nothing special
Interestingly the setStrokingColor is the only method accepting colors on the stream.
So I thought this is the way to color something in PDFBox.
BUT: I'm not getting any color to the text. So I guess this is a method for other types of content.
Does anybody know how to achieve a colored text in PDFBox?
You use
contentStream.setStrokingColor(1f,0.5f,0.2f);
But in PDFs text by default is not drawn by stroking a path but by filling it. Thus, you should try
contentStream.setNonStrokingColor(1f,0.5f,0.2f);
instead.
Using below code I am able to create a pdf doc with an image but I would like to place the image on top of an background colour, I tried bit on my side but not able to achieve it can any one help me in achieving this:
public class SimpleTable {
public static void main(String args[]) throws Exception {
//Loading an existing document
PDDocument doc = new PDDocument();
PDPage my_page = new PDPage();
//Retrieving the page
doc.addPage(my_page);
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("D:\\QRCode.png",doc);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, my_page);
PDImageXObject
//Drawing the image in the PDF document
contents.drawImage(pdImage, 70, 250);
contents.setNotStrokingColoar(Color.RED);
System.out.println("Image inserted");
//Closing the PDPageContentStream object
contents.close();
//Saving the document
doc.save("D:\\QRCode.pdf");
//Closing the document
doc.close();
}
}
Note: the background-colour occupancy will be same as image size
Put this before drawing your image and remove the fill that is in your current code:
contents.setNotStrokingColoar(Color.RED);
contents.addRect(70, 250, pdImage.getWidth(), pdImage.getHeight());
contents.fill();
Be aware that a background color will make it more difficult to scan the QR code because there'll be less contrast.
I am working with Apache PDFBox 2.0.8. My Objective is to convert a PDF into Image and enlarge the canvas and put the contents in the center so that i can put some header and footer in the remaining space.
My issue is that the canvas is getting enlarged but the contents are not getting centered, they are stick to the bottom.
public class PDFRescale {
public static void main(String[] args) {
try {
String pdfFilename = "/MuhimbiPOC/Templates/Source_doc_withheaderfooter.pdf";
PDDocument document = PDDocument.load(new File(pdfFilename));
PDFRenderer pdfRenderer = new PDFRenderer(document);
PDPage pge = new PDPage();
PDFRescale ps = new PDFRescale();
int pageCounter = 0;
for (PDPage page : document.getPages())
{
final PDRectangle mediaBox = pge.getMediaBox();
mediaBox.setUpperRightX((float) (mediaBox.getUpperRightX()));
mediaBox.setUpperRightY((float) (mediaBox.getUpperRightY() * 1.5));
mediaBox.setLowerLeftY((float) (mediaBox.getLowerLeftY() * 1.5));
// note that the page number parameter is zero based
page.setMediaBox(mediaBox);
BufferedImage bim = pdfRenderer.renderImageWithDPI(pageCounter, 140, ImageType.RGB);
// suffix in filename will be used as the file format
ImageIOUtil.writeImage(bim, pdfFilename + "-" + (pageCounter++) + ".png", 140);
}
System.out.println("Task Completed ... ");
document.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
My issue is that the canvas is getting enlarged but the contents are not getting centered, they are stick to the bottom.
That is your issue for PDF pages whose mediaBox.getLowerLeftY() is 0. While this is very common, it is not required. If you had worked with a more generic selection of PDFs, you'd have seen that your issue is that the former contents eventually can be anywhere, even off-screen!
The cause is that you do
mediaBox.setUpperRightY((float) (mediaBox.getUpperRightY() * 1.5));
mediaBox.setLowerLeftY((float) (mediaBox.getLowerLeftY() * 1.5));
This would only work if the origin was somewhere on the horizontal mid-screen axis.
Instead use something like
mediaBox.setUpperRightY(mediaBox.getUpperRightY() + mediaBox.getHeight() * 0.5f);
mediaBox.setLowerLeftY(mediaBox.getLowerLeftY() - mediaBox.getHeight() * 0.5f);
Another issue of your code: you only set the MediaBox and ignore the CropBox. pdfRenderer.renderImageWithDPI on the other hand uses the CropBox. Only for PDF pages without explicit CropBox your code enlarges the page area. For a generic solution you should also adapt the CropBox.
I am using PDFBox to generate reports in Java. One of my requirements is to create a PDF document which contains the company logo at the top of the page. I am not able to find the way to accomplish that.
I have the following method in a Java class:
public void createPdf() {
PDDocument document = null;
PDPage page = null;
ServletContext servletContext = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
try {
File f = new File("Afiliado_2.pdf");
if (f.exists() && !f.isDirectory()) {
document = PDDocument.load(new File("Afiliado_2.pdf"));
page = document.getPage(0);
} else {
document = new PDDocument();
page = new PDPage();
document.addPage(page);
}
PDImageXObject pdImage = PDImageXObject.createFromFile(
servletContext.getRealPath("/resources/images/logo.jpg"),
document);
PDPageContentStream contentStream = new PDPageContentStream(
document, page, AppendMode.APPEND, true);
contentStream.drawImage(pdImage, 0, 0);
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Afiliado_2.pdf");
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The image is currently appearing in the bottom of the PDF. I know the line I need to modify is contentStream.drawImage(pdImage, 0, 0); but what coordinates do I need to specify so that is appears in the top of the page?
Typically the coordinate system for a page in PDF starts at the lower left corner. So with
contentStream.drawImage(pdImage, 0, 0);
you are drawing your image at that point. You can get the boundaries of your page using
page.getMediaBox();
and use that to position your image e.g.
PDRectangle mediaBox = page.getMediaBox();
// draw with the starting point 1 inch to the left
// and 2 inch from the top of the page
contentStream.drawImage(pdImage, 72, mediaBox.getHeight() - 2 * 72);
where PDF files normally specify 72 points to 1 physical inch.
I'm writing a java app that creates a pdf from scratch using the pdfbox library.
I need to place a jpg image in one of the page.
I'm using this code:
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
/* ... */
/* code to add some text to the page */
/* ... */
InputStream in = new FileInputStream(new File("c:/myimg.jpg"));
PDJpeg img = new PDJpeg(document, in);
contentStream.drawImage(img, 100, 700);
contentStream.close();
document.save("c:/mydoc.pdf");
When I run the code, it terminates successfully, but if I open the generated pdf file using Acrobat Reader, the page is completely white and the image is not placed in it.
The text instead is correctly placed in the page.
Any hint on how to put my image in the pdf?
Definitely add the page to the document. You'll want to do that, but I've also noticed that PDFBox won't write out the image if you create the PDPageContentStream BEFORE the PDJpeg. It's unexplained why this is so, but if you look close at the source of ImageToPDF that's what they do. Create the PDPageContentStream after PDJpeg and it magically works.
...
PDJpeg img = new PDJpeg(document, in);
PDPageContentStream stream = new PDPageContentStream( doc, page );
...
Looks like you're missing just a document.addPage(page) call.
See also the ImageToPDF example class in PDFBox for some sample code.
this is how default constructor for PDPageContentStream looks like:
public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException
{
this(document, sourcePage, AppendMode.OVERWRITE, true, false);
}
Problem is AppendMode.OVERWRITE for me using another constructor with parameter PDPageContentStream.AppendMode.APPEND resolved a problem
For me this worked:
PDPageContentStream contentStream =
new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);