I want to add a image or text watermark to pdf file. I found some examples online, but my case is a little bit different.
I have an existing pdf template which is already populated with dynamic data and converted to byte[]. This generated bytes are later exported to pdf.
I would like to add the watermark to that generated bytes.
Something like:
byte[] addWatermark(byte[] generatedBytes){
byte[] bytesWithWatermark;
//add watermark to bytes
return bytesWithWatermark;
}
I just can't seem to figure out how to do this with iText.
You say you already have examples for applying watermarks using iText. As you already have a PDF, you should use code from an example that adds watermarks to existing PDFs. This should be an example that works with a PdfReader / PdfStamper pair, e.g. those here, which all have the structure
PdfReader reader = new PdfReader(SOME_SOURCE);
PdfStamper stamper = new PdfStamper(reader, SOME_TARGET_STREAM);
[... add watermark to all pages in stamper ...]
stamper.close();
reader.close();
To make these example fit into your addWatermark method, simply use your byte[] instead of SOME_SOURCE and a ByteArrayOutputStream instead of SOME_TARGET_STREAM:
byte[] addWatermark(byte[] generatedBytes) {
try (ByteArrayOutputStream target = new ByteArrayOutputStream()) {
PdfReader reader = new PdfReader(generatedBytes);
PdfStamper stamper = new PdfStamper(reader, target);
[... add watermark to all pages in stamper ...]
stamper.close();
reader.close();
return target.toByteArray();
}
}
PS As you used only the tag itext and not the tag itext7, I assumed you were looking for a solution for iText 5.5.x. But the same principle as applied here, i.e. using your byte[] as source argument and a ByteArrayOutputStream as target argument, will also allow you to make iText 7.x examples fit into your method frame.
Related
What I am trying to achieve is to replace a text in pdf file. I have the following code:
PdfReader reader = new PdfReader("test.pdf");
PdfDictionary dict = reader.getPageN(1);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object instanceof PRStream)
{
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
System.out.println(new String(data));
stream.setData(new String(data).replace("application", "HELLO WORLD").getBytes());
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("test-output.pdf"));
stamper.close();
reader.close();
When I trying to print out to see the data (System.out.println(new String(data))), "application" is showing as "ap)-4(plica)-3(tion", that's the reason why I failed to replace the text, any idea or other method that can achieve what I trying to achieve?
You will not be able to do this with iText.
Believe me, this is one of the most frustrating discoveries about PDFs: you can build them with iText, but you cannot go back later and replace text with something else, as you have in your example.
There really is not much you can do about it. Once text is there, you can't modify it.
All that notwithstanding, you can usually ADD new content (text, images, etc.) to an existing PDF. So... if you can alter the universe slightly and create a PDF with empty space in the correct size, you can go back later and use the PdfStamper class to "stamp" on another layer of graphical content.
More on this can be found in the iText documentation, and in this fine question:
How to add Content to a PDF using iText PdfStamper
I am using itext to fill a template pdf, but I want to add tag to the template pdf and to the elements that I am trying to fill into it.
The first step that I made is trying to insert tag for the element that I am trying to insert into, here my code:
PdfReader reader = new PdfReader("myTemplatepath");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos);
PdfWriter writer = stamper.getWriter();
writer.setTagged(); //Make document tagged
But when I am using writer.setTagged() I have the following error:
java.lang.IllegalArgumentException: Tagging must be set before opening
the document
I saw, in this Topic that the problem is that PdfStamper doesn't support tagging,and the best solution is to create a new PDF and tagged it so my question is :
Since the topic is from 2007, there is any new implementation about this?
If not, what is the best way to doing so? The template that I have is not so simple and It has editable elements ( that i fill automaticatily).
I want to create non-printable pdf with using jasper, however users can display pdf but they can't print pdf. I don't want any pdf password restriction. I've researched jasper documentation but i couldn't found anything about it.
Is there anyway to solve my issue? I've already thank to you for your helps.
You can use iText's PdfStamper to post-process your PDF :
byte[] pdfContent = /* your PDF content here */;
ByteArrayOutputStream stampedPdfContent = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(pdfContent);
PdfStamper stamper = new PdfStamper(reader, stampedPdfContent);
stamper.setEncryption(null, null, ~(PdfWriter.ALLOW_PRINTING), PdfWriter.STANDARD_ENCRYPTION_128);
stamper.close();
pdfContent = stampedPdfContent.toByteArray(); // your PDF is now non printable
I create a pdf document and specify few acro-fields. These acro-fields used to be filled by java itext library. This document is digitally signed after adding all required acro-fields.
We already set form filling property in digital signature but we have requirement to fill these acro-fields and make them read only after one time filling without invalidating digital signature.
Here is the code that I am using to fill this document -
String FILE = "/Users/xyz/Desktop/test1.pdf";
PdfReader reader = new PdfReader(pdfReader, new FileOutputStream(pdfTemplatePath), '\0', true);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(FILE), );
AcroFields form = stamper.getAcroFields();
form.setField("Name", "test 123");
stamper.close();
reader.close();
I am using lowagie itext library for filling pdf form.
Is there any way to fix this issue.
Thanks.
I want to add a word in a sentence of a PDF content.
For example:
This is a sample content.
I want to insert a word in that content like this output.
This is a nice sample content.
This is a sample code for itextPdf that I found in the internet. Assumed that the content already exists and we want to modify it by adding a text in a sentence.
try {
//Create PdfReader instance.
PdfReader pdfReader =
new PdfReader(SRC);
//Create PdfStamper instance.
PdfStamper pdfStamper = new PdfStamper(pdfReader,
new FileOutputStream(DEST));
//Create BaseFont instance.
BaseFont baseFont = BaseFont.createFont(
BaseFont.TIMES_ROMAN,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
//Get the number of pages in pdf.
int pages = pdfReader.getNumberOfPages();
System.out.println(pdfStamper.getOverContent(1));
//Iterate the pdf through pages.
for(int i=1; i<=pages; i++) {
//Contain the pdf data.
PdfContentByte pageContentByte =
pdfStamper.getOverContent(i);
pageContentByte.setFlatness(89);
pageContentByte.beginText();
//Set text font and size.
pageContentByte.setFontAndSize(baseFont, 14);
pageContentByte.setTextMatrix(50, 720);
//Write text
pageContentByte.setWordSpacing(12);
pageContentByte.showText("hello world");
pageContentByte.endText();
}
//Close the pdfStamper.
pdfStamper.close();
System.out.println("PDF modified successfully.");
} catch (Exception e) {
e.printStackTrace();
}
I tried itextPdf and PdfBox but neither of them would work.
I can get the objects in the pdf document using PDFStreamParser of pdfbox.
PDFOperator{Td}, COSArray{[COSString{Name }, COSFloat{163.994}, COSString{____________________________________________________}, COSFloat{-8.03223}, COSString{________________________________________________________}]}, PDFOperator{TJ}, COSInt{19}, PDFOperator{TL}, PDFOperator{T*}, COSArray{[COSString{T}, COSInt{36}, COSString{itle}, COSFloat{0.997925}, COSString{ }, COSFloat{-94.9982}, COSString{_____________________________________________________________________________________________________________}]}, PDFOperator{TJ}, PDFOperator{T*}, COSArray{[
How can I implement a code that inserts a text?
Not.
Pdf is not a wysiwyg format. Internally, it's more like a file containing code. It has instructions for moving around a cursor, and drawing text and graphics at the tip of the cursor.
Then there's the fact that most instructions get packaged into "objects". All objects get placed in a dictionary that uses byte-offsets to reference them.
So inserting anything in a pdf-document will cause problems on 2 levels.
You would mess up the byte-offset of everything in the document
You would need to unscramble all the existing rendering operations to make sense of the document (to derive structure like lines of text, paragraph, etc) so that you can properly re-flow the content after you've inserted something.
Hence my short answer. You can't. And that immediately explains why none of the pdf toolkits you've tried can do it. It's simply an insanely hard task.