Adding text to existing pdf which is closed using itextsharp - pdf-generation

Hi
I am creating PDF using itextsharp. Now my requirement is to add more text to the existing pdf. Is it possible if so then how can I do that?
Thanks Dipa

Yes, with certain limitations.
It is difficult, but not impossible, to determine what is already on an existing page.
If all you want to do is add "page X of Y" to the bottom left corner of all your pages, that's easy.
PdfReader reader = new PdfReader( inPath );
PdfStamper stamper = new PdfStamper( reader, new FileOutputStream( outPath ) );
BaseFont font = BaseFont.createFont(); // Helvetica, WinAnsiEncoding
for (int i = 0; i < reader.getNumberOfPages(); ++i) {
PdfContentByte overContent = stamper.getOverContent( i + 1 );
overContent.saveState();
overContent.beginText();
overContent.setFontAndSize( font, 10.0f );
overContent.setTextMatrix( xLoc, yLoc );
overContent.showText( "Page " + (i + 1) + " of " + reader.getNumberOfPages() );
overContent.endText();
overContent.restoreState();
}
stamper.close();
A big watermark isn't much more difficult. Adding things to a PDF at one or more predetermined locations is quite doable.
At the other end of the spectrum is "change text within existing paragraphs and reflow them". That's all but impossible. It would be much easier to rebuild the original PDF with the new data.
In fact, if at all possible, just rebuild them. You did it once, do it again.

Related

Writing Macro in ImageJ to open, change color, adjust brightness and resave microscope images

I'm trying to write a code in Image J that will:
Open all images in separate windows that contains "488" within a folder
Use look up tables to convert images to green and RGB color From ImageJ, the commands are: run("Green"); and run("RGB Color");
Adjust the brightness and contrast with defined values for Min and Max (same values for each image).
I know that the code for that is:
//run("Brightness/Contrast..."); setMinAndMax(value min, value max); run("Apply LUT");
Save each image in the same, original folder , in Tiff and with the same name but finishing with "processed".
I have no experience with Java and am very bad with coding. I tried to piece something together using code I found on stackoverflow and on the ImageJ website, but kept getting error codes. Any help is much appreciated!
I don't know if you still need it, but here is an example.
output_dir = "C:/Users/test/"
input_dir = "C:/Users/test/"
list = getFileList(input_dir);
listlength = list.length;
setBatchMode(true);
for (z = 0; z < listlength; z++){
if(endsWith(list[z], 'tif')==true ){
if(list[z].contains("488")){
title = list[z];
end = lengthOf(title)-4;
out_path = output_dir + substring(title,0,end) + "_processed.tif";
open(input_dir + title);
//add all the functions you want
run("Brightness/Contrast...");
setMinAndMax(1, 15);
run("Apply LUT");
saveAs("tif", "" + out_path + "");
close();
};
run("Close All");
}
}
setBatchMode(false);
I think it contains all the things you need. It opens all the images (in specific folder) that ends with tif and contains 488. I didn't completely understand what you want to do with each photo, so I just added your functions. But you probably won't have problems with adding more/different since you can get them with macro recorder.
And the code is written to open tif files. If you have tiff just be cerful that you change that and also change -4 to -5.

iText Image and transparency

I'm trying to add a PNG image to an existing pdf, but the transparency is converted to black color.
PdfReader reader = new PdfReader(pdfPath);
File f = new File(pdfPath);
String result = f.getParent() + File.separator + UUID.randomUUID().toString() + ".pdf";
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(result));
Image image = Image.getInstance(ImageIO.read(new File(imagePath)), null);
PdfImage stream = new PdfImage(image, null, null);
PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
image.setDirectReference(ref.getIndirectReference());
image.setAbsolutePosition(30, 300);
PdfContentByte canvas = stamper.getOverContent(1);
canvas.addImage(image);
stamper.close();
reader.close();
How can I keep transparency?
First this: I am violating the policy at iText Software by answering this question. You are using an old version of iText, and the policy dictates that voluntary support on iText 5 or earlier has stopped. You should either use iText 7, or you should get a support contract if you still want support for an old iText version.
However, I am curious. I want to know where you found this clunky code (or why you decided to write this code):
Image image = Image.getInstance(ImageIO.read(new File(imagePath)), null);
PdfImage stream = new PdfImage(image, null, null);
PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
image.setDirectReference(ref.getIndirectReference());
image.setAbsolutePosition(30, 300);
PdfContentByte canvas = stamper.getOverContent(1);
canvas.addImage(image);
You don't need ImageIO and you don't need to create a PdfImage, nor do you need to add that image to the body of a PDF file. The code you are using is code specialists would use for a very particular purpose. If you know that particular purpose, please explain.
If adding an image at an absolute position is all you want to do (that's a general purpose, not a particular purpose), your code should be as simple as this:
Image image = Image.getInstance(imagePath);
image.setAbsolutePosition(30, 300);
PdfContentByte canvas = stamper.getOverContent(1);
canvas.addImage(image);
In this case, you don't have to worry about the image mask; iText will take care of that for you.
Please also explain why you're using an outdated version of iText instead of iText 7. If you want your application to be future-proof, you should upgrade to iText 7 now (to avoid wasting time later).

Set text over a scanned document in itext

I've made a lot of research on this subject but everything I find is everytime "use the function getOverContent of the stamper". I made this and it still not working.
I made a programm which merge together the PDFs of a repertory, than it paginates this new document (I hope you can follow what I'm writting). The original PDFs are self made (direct saved in PDF) or not (scanned). That's with these last ones where there are trouble. The pagination shows on the firsts but not on the seconds (it exists probably, but it should be behind the image)!
Here is the code for the pagination, has someone THE idea, where I'm mistaken?
PdfReader reader = new PdfReader(source);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destination));
for (int i = start + 1; i <= reader.getNumberOfPages(); i++) {
Phrase noPage = new Phrase((i - start) + "", new Font(FontFamily.COURIER, 14));
float x = reader.getPageSize(i).getRight(20);
float y = reader.getPageSize(i).getTop(20);
PdfContentByte content = stamper.getOverContent(i);
content.beginText();
ColumnText.showTextAligned(content,Element.ALIGN_CENTER, noPage, x, y, 0);
content.endText();
}
stamper.close();
reader.close();
Thanks
After Answer from Bruno, I've made the following:
PdfReader reader = new PdfReader(source);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destination));
for (int i = start + 1; i <= reader.getNumberOfPages(); i++) {
Phrase noPage = new Phrase((i - start) + "", new Font(FontFamily.COURIER, 14));
float x = reader.getCropBox(i).getRight(20);
float y = reader.getCropBox(i).getTop(20);
PdfContentByte content = stamper.getOverContent(i);
ColumnText.showTextAligned(content,Element.ALIGN_CENTER, noPage, x, y, 0);
}
stamper.close();
reader.close();
But it's still not working
For examples: https://www.transfernow.net/24axn1g4wq4l
The original PDFs are self made (direct saved in PDF) or not (scanned). That's with these last ones where there are trouble. The pagination shows on the firsts but not on the seconds (it exists probably, but it should be behind the image)!
The problem is not that the second type of PDFs is scanned but that it uses page rotation.
When a page is rotated, iText inserts a coordinate system rotation instruction at the start of the undercontent and overcontent which ensures that any text drawn without further transformation is displayed upright on the rotated page.
This rotation of the coordinate system obviously needs to be considered when choosing absolute coordinates.
Thus, instead of
reader.getPageSize(i)
you should use
reader.getPageSizeWithRotation(i)
Alternatively you can switch of this iText mechanism using
stamper.setRotateContents(false);
and then consider the presence of page rotation explicitly in all your following operations.

pdfbox - rotation issue

As part of a project I am realizing, there are given pdfdocuments which include forms as JPEG Images within A4 pages inside this documents. If have to extract those JPGs out of the PDF. Later on those JPGs are used to build PDF Documents again.
When I simply open up those Documents with any PDFViewer they seem to have no rotation at all, at least it is not visible. So like this icon the have vertical format.
but when I use this sample code to extract the images :
PDDocument doc = PDDocument.load("/path/to/file);
List pages = doc.getDocumentCatalog().getAllPages();
Iterator iter = pages.iterator();
int i = 0;
while (iter.hasNext()) {
PDPage page = (PDPage) iter.next();
System.out.println(page.getRotation());
System.out.println("ROTATION = " + page.getRotation());;
PDResources resources = page.getResources();
Map pageImages = resources.getXObjects();
if (pageImages != null) {
Iterator imageIter = pageImages.keySet().iterator();
while (imageIter.hasNext()) {
String key = (String) imageIter.next();
if(((PDXObjectImage) pageImages.get(key)) instanceof PDXObjectImage){
PDXObjectImage image = (PDXObjectImage) pageImages.get(key);
image.write2file("/path/to/file" + i);
}
i ++;
}
}
}
all extracted JPGs are horizontal format. Further the sysout on the page.rotation tells me that the rotation is set to 270°.
How is that possible? 270 is set, but the PDF is shown vertical (I am no expert on PDF). I even did page.setRotate(0) before extracting the JPGs, but the images still remain horizontally. I read the following Thread telling how to rotate images before drawing them on the pdf. But i need to rotate them before writing them on the filesystem. What is the best way to achieve that?
Unfortunately, I can not attach any of the documents since they are confidential.

append image to EXISTING pdf using itextsharp

The following code is very good at putting a single page into a pdf.
It does not work for subsequent pages.
If the stream is an existing pdf file the image is replaced. How do I get NewPage() to actually create a new page and add the image at the end.
using (Stream ms = GetStream()) {
Document doc = new Document(PageSize.A4);
var writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
if (!doc.NewPage())
throw new InvalidOperationException("NewPage failed.");
PDFImage jpg = PDFImage.GetInstance(image, ImageFormat.Jpeg);
jpg.Alignment = Element.ALIGN_CENTER;
jpg.ScaleToFit(PageSize.A4.Width, PageSize.A4.Height);
doc.Add(jpg);
doc.Close();
}
Calling doc.NewPage() doesn't do anything when there's nothing on the current page. There are at least 3 options:
1) Add something invisible to the current page. An empty paragraph, some white space to the PdfContentByte, whatever.
2) Tell your PDF document "no, its really not empty, take my word": PdfDocument.PageEmpty =false;
3) Don't throw when NewPage returns false. That's perfectly acceptable under the circumstances.
I'd go with #3 personally.

Resources