Setting a text style to underlined in PDFBox - java

I'm trying to add underlined text to a blank pdf page using PDFBox, but I haven't been able to find any examples online. All questions on stackoverflow point to extracting underlined text, but not creating it. Has this function not been implemented for PDFBox? Looking at the PDFBox documentation, it seems that fonts are pre-rendered as bold, italic, and regular.
For example, Times New Roman Regular is denoted as:
PDFont font = PDType1Font.TIMES_ROMAN.
Times New Roman Bold is denoted as:
PDFont font = PDType1Font.TIMES_BOLD
Italicized is denoted as:
PDFont font = PDType1Font.TIMES_ITALIC
There seems to be no underlined option. Is there anyway to underline text, or is this not a feature?

I'm not sure if this is a better alternative or not, but I followed Tilman Hausherr and drew a line in comparison to my text. For instance, I have the following:
public processPDF(int xOne, int yOne, int xTwo, int yTwo)
{
//create pdf and its contents for one page
PDDocument document = new PDDocument();
File file = new File("hello.pdf");
PDPage page = new PDPage();
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream;
try {
//create content stream
contentStream = new PDPageContentStream(document, page);
//being to create our text for our page
contentStream.beginText();
contentStream.setFont( font, largeTitle);
//position of text
contentStream.moveTextPositionByAmount(xOne, yOne, xTwo, yTwo);
contentStream.drawString("Hello");
contentStream.endText();
//begin to draw our line
contentStream.drawLine(xOne, yOne - .5, xTwo, yYwo - .5);
//close and save document
document.save(file);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
where our parameters xOne, yOne, xTwo, and yTwo are our locations of the text. The line has us subtract .5 from yOne and yTwo to move it a pinch below our text location, ultimately setting it to look like underlined text.
There may be better ways, but this was the route I went.

I use below function for underlined the string.
public class UnderlineText {
PDFont font = PDType1Font.HELVETICA_BOLD;
float fontSize = 10f;
String str = "Hello";
public static void main(String[] args) {
new UnderlineText().generatePDF(20, 200);
}
public void generatePDF(int sX, int sY)
{
//create pdf and its contents for one page
PDDocument document = new PDDocument();
File file = new File("underlinePdfbox.pdf");
PDPage page = new PDPage();
PDPageContentStream contentStream;
try {
document.addPage(page);
//create content stream
contentStream = new PDPageContentStream(document, page);
//being text for our page
contentStream.beginText();
contentStream.setFont( font, fontSize);
contentStream.newLineAtOffset(sX, sY);
contentStream.showText(str);
contentStream.endText();
//Draw Underline
drawLine(contentStream, str, 1, sX, sY, -2);
//close and save document
contentStream.close();
document.save(file);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void drawLine(PDPageContentStream contentStream, String text, float lineWidth, float sx, float sy, float linePosition) throws IOException {
//Calculate String width
float stringWidth = fontSize * font.getStringWidth(str) / 1000;
float lineEndPoint = sx + stringWidth;
//begin to draw our line
contentStream.setLineWidth(lineWidth);
contentStream.moveTo(sx, sy + linePosition);
contentStream.lineTo(lineEndPoint, sy + linePosition);
contentStream.stroke();
}
}
drawLine is a function which i created for drawing a line for specific string. You can adjust line as per specification using position attribute.
Minus (-) value in position field create under line. you can use positive value for over-line and stroke-line.(For example -2 for underline, 10 for over-line, 2 for stroke-line for above code)
Also you can manage the width for line.

Try this answer:
highlight text using pdfbox when it's location in the pdf is known
This method using PDAnnotationTextMarkup, it has four values
/**
* The types of annotation.
*/
public static final String SUB_TYPE_HIGHLIGHT = "Highlight";
/**
* The types of annotation.
*/
public static final String SUB_TYPE_UNDERLINE = "Underline";
/**
* The types of annotation.
*/
public static final String SUB_TYPE_SQUIGGLY = "Squiggly";
/**
* The types of annotation.
*/
public static final String SUB_TYPE_STRIKEOUT = "StrikeOut";
Hope it helps

Related

Unable to extract values from PDF for specific coordinates using java apache pdfbox

My task is to extract text from PDF for a specific coordinates.
I have used Apache Pdfbox client for data extraction .
To get the x, y , height and width coordinates from the PDF i am using PDF X change tool which is in Millimeter. When i pass the value in the rectangle the values are not getting empty value.
public String getTextUsingPositionsUsingPdf(String pdfLocation, int pageNumber, double x, double y, double width,
double height) throws IOException {
String extractedText = "";
// PDDocument Creates an empty PDF document. You need to add at least
// one page for the document to be valid.
// Using load method we can load a PDF document
PDDocument document = null;
PDPage page = null;
try {
if (pdfLocation.endsWith(".pdf")) {
document = PDDocument.load(new File(pdfLocation));
int getDocumentPageCount = document.getNumberOfPages();
System.out.println(getDocumentPageCount);
// Get specific page. THe parameter is pageindex which starts with // 0. If we need to
// access the first page then // the pageIdex is 0 PDPage
if (getDocumentPageCount > 0) {
page = document.getPage(pageNumber + 1);
} else if (getDocumentPageCount == 0) {
page = document.getPage(0);
}
// To create a rectangle by passing the x axis, y axis, width and height
Rectangle2D rect = new Rectangle2D.Double(x, y, width, height);
String regionName = "region1";
// Strip the text from PDF using PDFTextStripper Area with the
// help of Rectangle and named need to given for the rectangle
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
stripper.addRegion(regionName, rect);
stripper.extractRegions(page);
System.out.println("Region is " + stripper.getTextForRegion("region1"));
extractedText = stripper.getTextForRegion("region1");
} else {
System.out.println("No data return");
}
} catch (IOException e) {
System.out.println("The file not found" + "");
} finally {
document.close();
}
// Return the extracted text and this can be used for assertion
return extractedText;
}
Please suggest whether my way is correct or not..
I have used this PDF tutorialspoint.com/uipath/uipath_tutorial.pdf.. Where i am trying to find the text "a part of contests" which is have x = 55.6 mm y = 168.8 width = 210.0 mm and height = 297.0. But i am getting empty value
I tested your method with those inputs:
System.out.println("Extracting like Venkatachalam Neelakantan from uipath_tutorial.pdf\n");
float MM_TO_UNITS = 1/(10*2.54f)*72;
String text = getTextUsingPositionsUsingPdf("src/test/resources/mkl/testarea/pdfbox2/extract/uipath_tutorial.pdf",
0, 55.6 * MM_TO_UNITS, 168.8 * MM_TO_UNITS, 210.0 * MM_TO_UNITS, 297.0 * MM_TO_UNITS);
System.out.printf("\n---\nResult:\n%s\n", text);
(ExtractText test testUiPathTutorial)
and got the result
part of contents of this e-book in any manner without written consent
te the contents of our website and tutorials as timely and as precisely as
, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
guarantee regarding the accuracy, timeliness or completeness of our
tents including this tutorial. If you discover any errors on our website or
ease notify us at contact#tutorialspoint.com
i
Assuming you actually were looking for "a part of contents", not "a part of contests", merely the 'a' is missing; probably when measuring you looked for the beginning of the visible letter drawing but the actual glyph origin is a bit before that. If you choose a slightly smaller x, e.g. 54.6 mm, you'll also get the 'a'.
It obviously is no surprise that you get more than "a part of contents", considering the width and height of your rectangle.
Should you wonder about the MM_TO_UNITS constant, have a look at this answer.

create a one page PDF from two PDFs using PDFBOX

I have a small (quarter inch) one page PDF I created with PDFBOX with text (A). I want to put that small one page PDF (A) on the top of an existing PDF page (B), preserving the existing content of the PDF page (B). In the end, I will have a one page PDF, representing the small PDF on top(A), and the existing PDF intact making up the rest (B). How can I accomplish this with PDFBOX?
To join two pages one atop the other onto one target page, you can make use of the PDFBox LayerUtility for importing pages as form XObjects in a fashion similar to PDFBox SuperimposePage example, e.g. with this helper method:
void join(PDDocument target, PDDocument topSource, PDDocument bottomSource) throws IOException {
LayerUtility layerUtility = new LayerUtility(target);
PDFormXObject topForm = layerUtility.importPageAsForm(topSource, 0);
PDFormXObject bottomForm = layerUtility.importPageAsForm(bottomSource, 0);
float height = topForm.getBBox().getHeight() + bottomForm.getBBox().getHeight();
float width, topMargin, bottomMargin;
if (topForm.getBBox().getWidth() > bottomForm.getBBox().getWidth()) {
width = topForm.getBBox().getWidth();
topMargin = 0;
bottomMargin = (topForm.getBBox().getWidth() - bottomForm.getBBox().getWidth()) / 2;
} else {
width = bottomForm.getBBox().getWidth();
topMargin = (bottomForm.getBBox().getWidth() - topForm.getBBox().getWidth()) / 2;
bottomMargin = 0;
}
PDPage targetPage = new PDPage(new PDRectangle(width, height));
target.addPage(targetPage);
PDPageContentStream contentStream = new PDPageContentStream(target, targetPage);
if (bottomMargin != 0)
contentStream.transform(Matrix.getTranslateInstance(bottomMargin, 0));
contentStream.drawForm(bottomForm);
contentStream.transform(Matrix.getTranslateInstance(topMargin - bottomMargin, bottomForm.getBBox().getHeight()));
contentStream.drawForm(topForm);
contentStream.close();
}
(JoinPages method join)
You use it like this:
try ( PDDocument document = new PDDocument();
PDDocument top = ...;
PDDocument bottom = ...) {
join(document, top, bottom);
document.save("joinedPage.pdf");
}
(JoinPages test testJoinSmallAndBig)
The result looks like this:
Just as an additional point to #mkl's answer.
If anybody is looking to scale the PDFs before placing them on the page use,
contentStream.transform(Matrix.getScaleInstance(<scaling factor in x axis>, <scaling factor in y axis>)); //where 1 is the scaling factor if you want the page as the original size
This way you can rescale your PDFs.

Cannot capture annotations in a PDImageXObject using PDFBox

I am highlighting (in green) certain words on each page of my input pdf document using PDAnnotationTextMarkup. A sample screenshot is seen below;
However, when I crop this part of the page and try to save it as a PDImageXObject, I get the following result;
The code I am using to crop the image is as follows;
public PDImageXObject cropAndSaveImage(int pageNumber, Rectangle dimensions)
{
PDImageXObject pdImage = null;
// Extract arguments from the rectangle object
float x = dimensions.getXValue();
float y = dimensions.getYValue();
float w = dimensions.getWidth();
float h = dimensions.getHeight();
PDRectangle pdRectangle;
int pageResolution = 140;
try{
// Fetch the source page
PDPage sourcePage = document.getPage(pageNumber-1);
// Calculate height of the source page
PDRectangle mediaBox = sourcePage.getMediaBox();
float sourcePageHeight = mediaBox.getHeight();
// Fetch the original crop box of the page
PDRectangle originalCrop = sourcePage.getCropBox();
/*
* PDF Crop Box - Here we initialize the rectangle area
* that is needed to crop a region from the PDF document
*/
if(pageOriginShifted)
{
pdRectangle = new PDRectangle(x, sourcePageHeight - y, w, h);
}
else
{
pdRectangle = new PDRectangle(x, y, w, h);
}
// Crop the required rectangle from the source page
sourcePage.setCropBox(pdRectangle);
// PDF renderer
PDFRenderer renderer = new PDFRenderer(document);
// Convert to an image
BufferedImage bufferedImage = renderer.renderImageWithDPI(pageNumber-1, pageResolution, ImageType.RGB);
pdImage = LosslessFactory.createFromImage(document, bufferedImage);
// Restore the original page back to the document
sourcePage.setCropBox(originalCrop);
return pdImage;
}catch(Exception e)
{
Logger.logWithoutTimeStamp(LOG_TAG + "cropAndSaveImage()", Logger.ERROR, e);
}
return null;
}
I am quite perplexed on why the highlighted text in green won't show up. Any help in this regard is highly appreciated (I cannot attach the input PDF document owing to privacy issues).
Thanks in advance,
Bharat.

PDFBOX unable to find number of pixels which contain a particular character

I am using PDFBOX for pdf creation. In pdfbox is there any function which will give the font size in pixels? For example letters A and a, will take different spaces for printing. Where obviosely A will take more pixels than a. How can I get find number of pixels supposed to take a character or a word?
First of all the concept of pixels is a bit vague.
Generally a document is of a certain size, e.g. inches/cm etc.
The javadocs for PDFBox shows that PDFont has a few methods to determine the width of a string or character.
Take a look at for example these pages:
getStringWidth(String text)
getWidth(int code)
getWidthFromFont(int code)
These units are in 1/1000 of an Em. Also see this page.
For a full example:
float fontSize = 12;
String text = "a";
PDRectangle pageSize = PDRectangle.A4;
PDFont font = PDType1Font.HELVETICA_BOLD;
PDDocument doc = new PDDocument();
PDPage page = new PDPage(pageSize);
doc.addPage(page);
PDPageContentStream stream = new PDPageContentStream(doc,page);
stream.setFont( font, fontSize );
// charWidth is in points multiplied by 1000.
double charWidth = font.getStringWidth(text);
charWidth *= fontSize; // adjust for font-size.
stream.beginText();
stream.moveTextPositionByAmount(0,10);
float widthLeft = pageSize.getWidth();
widthLeft *= 1000.0; //due to charWidth being x1000.
while(widthLeft > charWidth){
stream.showText(text);
widthLeft -= charWidth;
}
stream.close();
// Save the results and ensure that the document is properly closed:
doc.save( "example.pdf");
doc.close();

Watermarking with PDFBox

I am trying to add a watermark to a PDF specifically with PDFBox. I've been able to get the image to appear on each page, but it loses the background transparency because it appears as though PDJpeg converts it to a JPG. Perhaps there's a way to do it using PDXObjectImage.
Here is what I have written thus far:
public static void watermarkPDF(PDDocument pdf) throws IOException
{
// Load watermark
BufferedImage buffered = ImageIO.read(new File("C:\\PDF_Test\\watermark.png"));
PDJpeg watermark = new PDJpeg(pdf, buffered);
// Loop through pages in PDF
List pages = pdf.getDocumentCatalog().getAllPages();
Iterator iter = pages.iterator();
while(iter.hasNext())
{
PDPage page = (PDPage)iter.next();
// Add watermark to individual page
PDPageContentStream stream = new PDPageContentStream(pdf, page, true, false);
stream.drawImage(watermark, 100, 0);
stream.close();
}
try
{
pdf.save("C:\\PDF_Test\\watermarktest.pdf");
}
catch (COSVisitorException e)
{
e.printStackTrace();
}
}
UPDATED ANSWER (Better version with easy way to watermark, thanks to the commentators below and #okok who provided input with his answer)
If you are using PDFBox 1.8.10 or above, you can add watermark to your PDF document easily with better control over what pages needs to be watermarked. Assuming you have a one page PDF document that has the watermark image, you can overlay this on the document you want to watermark as follows.
Sample Code using 1.8.10
import java.util.HashMap;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.Overlay;
public class TestPDF {
public static void main(String[] args) throws Exception{
PDDocument realDoc = PDDocument.load("originaldocument.pdf");
//the above is the document you want to watermark
//for all the pages, you can add overlay guide, indicating watermark the original pages with the watermark document.
HashMap<Integer, String> overlayGuide = new HashMap<Integer, String>();
for(int i=0; i<realDoc.getPageCount(); i++){
overlayGuide.put(i+1, "watermark.pdf");
//watermark.pdf is the document which is a one page PDF with your watermark image in it. Notice here that you can skip pages from being watermarked.
}
Overlay overlay = new Overlay();
overlay.setInputPDF(realDoc);
overlay.setOutputFile("final.pdf");
overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
overlay.overlay(overlayGuide,false);
//final.pdf will have the original PDF with watermarks.
Sample using PDFBox 2.0.0 Release candidate
import java.io.File;
import java.util.HashMap;
import org.apache.pdfbox.multipdf.Overlay;
import org.apache.pdfbox.pdmodel.PDDocument;
public class TestPDF {
public static void main(String[] args) throws Exception{
PDDocument realDoc = PDDocument.load(new File("originaldocument.pdf"));
//the above is the document you want to watermark
//for all the pages, you can add overlay guide, indicating watermark the original pages with the watermark document.
HashMap<Integer, String> overlayGuide = new HashMap<Integer, String>();
for(int i=0; i<realDoc.getNumberOfPages(); i++){
overlayGuide.put(i+1, "watermark.pdf");
//watermark.pdf is the document which is a one page PDF with your watermark image in it.
//Notice here, you can skip pages from being watermarked.
}
Overlay overlay = new Overlay();
overlay.setInputPDF(realDoc);
overlay.setOutputFile("final.pdf");
overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
overlay.overlay(overlayGuide);
}
}
If you want to use the new package org.apache.pdfbox.tools.OverlayPDF for overlays you can do this way. (Thanks the poster below)
String[] overlayArgs = {"C:/Examples/foreground.pdf", "C:/Examples/background.pdf", "C:/Examples/resulting.pdf"};
OverlayPDF.main(overlayArgs);
System.out.println("Overlay finished.");
OLD ANSWER Inefficient way, not recommended.
Well, OP asked how to do it in PDFBox, the first answer looks like an example using iText. Creating a watermark in PDFBox is really simple. The trick is, you should have an empty PDF document with the watermark image. Then all you have to do is Overlay this watermark document on the document that you want to add the watermark to.
PDDocument watermarkDoc = PDDocument.load("watermark.pdf");
//Assuming your empty document with watermark image in it.
PDDocument realDoc = PDDocument.load("document-to-be-watermarked.pdf");
//Let's say this is your document that you want to watermark. For example sake, I am opening a new one, you would already have a reference to PDDocument if you are creating one
Overlay overlay = new Overlay();
overlay.overlay(realDoc,watermarkDoc);
watermarkDoc.save("document-now-watermarked.pdf");
Caution: You should make sure you match the number of pages in both document..Otherwise, you would end up with a document with number of pages matching the one which has least number of pages. You can manipulate the watermark document and duplicate the pages to match your document.
Hope this helps.!
Just made this piece of code to add (transparent) images (jpg, png, gif) to a pdf page with pdfbox:
/**
* Draw an image to the specified coordinates onto a single page. <br>
* Also scaled the image with the specified factor.
*
* #author Nick Russler
* #param document PDF document the image should be written to.
* #param pdfpage Page number of the page in which the image should be written to.
* #param x X coordinate on the page where the left bottom corner of the image should be located. Regard that 0 is the left bottom of the pdf page.
* #param y Y coordinate on the page where the left bottom corner of the image should be located.
* #param scale Factor used to resize the image.
* #param imageFilePath Filepath of the image that is written to the PDF.
* #throws IOException
*/
public static void addImageToPage(PDDocument document, int pdfpage, int x, int y, float scale, String imageFilePath) throws IOException {
// Convert the image to TYPE_4BYTE_ABGR so PDFBox won't throw exceptions (e.g. for transparent png's).
BufferedImage tmp_image = ImageIO.read(new File(imageFilePath));
BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
image.createGraphics().drawRenderedImage(tmp_image, null);
PDXObjectImage ximage = new PDPixelMap(document, image);
PDPage page = (PDPage)document.getDocumentCatalog().getAllPages().get(pdfpage);
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
contentStream.drawXObject(ximage, x, y, ximage.getWidth()*scale, ximage.getHeight()*scale);
contentStream.close();
}
Example:
public static void main(String[] args) throws Exception {
String pdfFilePath = "C:/Users/Nick/Desktop/pdf-test.pdf";
String signatureImagePath = "C:/Users/Nick/Desktop/signature.png";
int page = 0;
PDDocument document = PDDocument.load(pdfFilePath);
addImageToPage(document, page, 0, 0, 0.5f, signatureImagePath);
document.save("C:/Users/Nick/Desktop/pdf-test-neu.pdf");
}
This worked for me with jdk 1.7 and bcmail-jdk16-140.jar, bcprov-jdk16-140.jar, commons-logging-1.1.3.jar, fontbox-1.8.3.jar, jempbox-1.8.3.jar and pdfbox-1.8.3.jar.
#Androidman : Addition to https://stackoverflow.com/a/9382212/7802973
It seems like many methods are removed with each version of PDFBox. So that code will not work on PDFBox 2.0.7.
Overlay overlay = new Overlay();
overlay.setInputPDF(realDoc);
// ** The method setOutputFile(String) is undefined for the type Overlay **
overlay.setOutputFile("final.pdf")
Instead, use void org.apache.pdfbox.pdmodel.PDDocument.save(String fileName), I think:
PDDocument realDoc = PDDocument.load(new File("originaldocument.pdf"));
//the above is the document you want to watermark
//for all the pages, you can add overlay guide, indicating watermark the original pages with the watermark document.
HashMap<Integer, String> overlayGuide = new HashMap<Integer, String>();
for(int i=0; i<realDoc.getNumberOfPages(); i++){
overlayGuide.put(i+1, "watermark.pdf");
//watermark.pdf is the document which is a one page PDF with your watermark image in it.
//Notice here, you can skip pages from being watermarked.
}
Overlay overlay = new Overlay();
overlay.setInputPDF(realDoc);
overlay.overlay(overlayGuide).save("final.pdf");
overlay.close();
Edit:
I am using org.apache.pdfbox.tools.OverlayPDF for overlays now and it works just fine. The code looks like this:
String[] overlayArgs = {"C:/Examples/foreground.pdf", "C:/Examples/background.pdf", "C:/Examples/resulting.pdf"};
OverlayPDF.main(overlayArgs);
System.out.println("Overlay finished.");
As I had not enough reputation to add a comment, I thought it'd be appropiate to add this in a new answer.
There is another Overlay class within util package, that saves you from creating a pdf with same number of pages as the source document and then doing the overlay.
To understand its usage, take a look at pdfbox source code, specifically the OverlayPDF class.
This is how I was able to add a text watermark with the date using PdfBox 2.0.x in C#. It centres the watermark at the top of the page.
public static void AddWatermark(string fileName)
{
StringBuilder sb = new StringBuilder();
sb.Append("watermark_text ");
sb.Append(DateTime.Now.ToString());
string waterMarkText = sb.ToString();
PDDocument origDoc = PDDocument.load(new java.io.File(fileName));
PDPageTree allPages = origDoc.getPages();
PDFont font = PDType1Font.HELVETICA_BOLD;
for (int i = 0, len = allPages.getCount(); i < len; ++i)
{
PDPage pg = (PDPage)allPages.get(i);
AddWatermarkText(origDoc, pg, font, waterMarkText);
}
origDoc.save(fileName);
origDoc.close();
}
static void AddWatermarkText(PDDocument doc, PDPage page, PDFont font, string text)
{
using (PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true))
{
float fontHeight = 30;
float width = page.getMediaBox().getWidth();
float height = page.getMediaBox().getHeight();
float stringWidth = font.getStringWidth(text) / 1000 * fontHeight;
float x = (width / 2) - (stringWidth / 2);
float y = height - 25;
cs.setFont(font, fontHeight);
PDExtendedGraphicsState gs = new PDExtendedGraphicsState();
gs.setNonStrokingAlphaConstant(new java.lang.Float(0.2f));
gs.setStrokingAlphaConstant(new java.lang.Float(0.2f));
gs.setBlendMode(BlendMode.MULTIPLY);
gs.setLineWidth(new java.lang.Float(3f));
cs.setGraphicsStateParameters(gs);
cs.setNonStrokingColor(Color.red);
cs.setStrokingColor(Color.red);
cs.beginText();
cs.newLineAtOffset(x, y);
cs.showText(text);
cs.endText();
}
}
pdfbox c# watermark pdf
Adding to the answer by #Droidman If your using version 2.0.21 and above you can directly overlay on PDDocument. Sample code as follows.
PDDocument realDoc = pdfGenerator.getDocument();
HashMap<Integer, PDDocument> overlayGuide = new HashMap<>();
for (int i = 0; i < realDoc.getNumberOfPages(); i++) {
overlayGuide.put(i + 1, document);
}
Overlay overlay = new Overlay();
overlay.setInputPDF(realDoc);
overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
overlay.overlayDocuments(overlayGuide);
Look at this method, whitch add a watermark image in pdf sources using PDFBOX library
/**
* Coloca una imagen como marca de agua en un pdf en una posición especifica
*
* #param buffer
* flujo de bytes que contiene el pdf original
*
* #param imageFileName
* nombre del archivo de la imagen a colocar
*
* #param x
* posición x de la imagen en el pdf
*
* #param y
* posición y de la imagen en el pdf
*
* #param under
* determina si la marca se pone encima o por debajo de la factura
*
* #return flujo de bytes resultante que contiene el pdf modificado
*
* #throws IOException
* #throws DocumentException
*/
public static byte[] addWaterMarkImageToPDF(byte[] buffer,
String imageFileName, int x, int y, boolean under) throws IOException,
DocumentException {
logger.debug("Agregando marca de agua:"+imageFileName);
PdfReader reader = new PdfReader(buffer);
ByteArrayOutputStream arrayOutput = new ByteArrayOutputStream();
OutputStream output = new BufferedOutputStream(arrayOutput);
PdfStamper stamper = new PdfStamper(reader, output);
com.lowagie.text.Image img = com.lowagie.text.Image
.getInstance(imageFileName);
img.setAbsolutePosition(x, y);
img.scalePercent(SCALE_PER);
PdfContentByte pdfContent;
int total = reader.getNumberOfPages() + 1;
for (int i = 1; i < total; i++) {
pdfContent = (under)?stamper.getUnderContent(i):
stamper.getOverContent(i);
pdfContent.addImage(img);
}
stamper.close();
output.flush();
output.close();
return arrayOutput.toByteArray();
}

Categories

Resources