adding a textbox to the right corner of the existing pdf using ITextSharp in C# - itext

I tiied to add a TextBox to the right corner of the existing pdf using c#, but im unable to get it done. I have wrote the following code,but it is not helping in solving the problem, can any body please suggest me
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
PdfReader.unethicalreading = true;
Paragraph p = new Paragraph();
Document doc = new Document();
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
PdfContentByte canvas = stamper.GetOverContent(1);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
//PdfContentByte cb = null;
//PdfImportedPage page;
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
var size1 = reader.GetPageSize(i);
w = size1.Width;
h = size1.Height;
stamper.FormFlattening = true;
TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(0, 0, 300, 100), displaytext);
//Change the orientation of the text
tf.Rotation = 0;
stamper.AddAnnotation(tf.GetTextField(), i);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(str, bytes);

As the OP clarified in comments to the question, he wants
to add the text as a page content in the right bottom corner of the page and
the page content previously existing there to be removed.
A simple implementation of this would include
first covering the existing page content with a filled rectangle and
then writing text there.
These tasks can be achieved with these helper methods:
void EmptyTextBoxSimple(PdfStamper stamper, int pageNumber, Rectangle boxArea, BaseColor fillColor)
{
PdfContentByte canvas = stamper.GetOverContent(pageNumber);
canvas.SaveState();
canvas.SetColorFill(fillColor);
canvas.Rectangle(boxArea.Left, boxArea.Bottom, boxArea.Width, boxArea.Height);
canvas.Fill();
canvas.RestoreState();
}
and
ColumnText GenerateTextBox(PdfStamper stamper, int pageNumber, Rectangle boxArea)
{
PdfContentByte canvas = stamper.GetOverContent(pageNumber);
ColumnText columnText = new ColumnText(canvas);
columnText.SetSimpleColumn(boxArea);
return columnText;
}
E.g. like this:
using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
Rectangle cropBox = reader.GetCropBox(1);
Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
columnText.Go();
}
For this source page
the sample code generates this
Addendum
In a comment the OP indicated
it is working for all files but for some pdf files it is displaying in the middle
Eventually he supplied a sample file for which the issue occurs. And indeed, with this file the issue could be reproduced.
The cause for the issue is that the pages in the sample file use page rotation, something that iText (only) partially allows users to ignore. In particular iText automatically rotates text to be upright after rotation and transforms coordinates, but when retrieving the cropbox of a page, one still has to apply rotation before making use of it coordinates. Thus, a more complete example would be like this:
using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
Rectangle cropBox = reader.GetCropBox(1);
int rotation = reader.GetPageRotation(1);
while (rotation > 0)
{
cropBox = cropBox.Rotate();
rotation -= 90;
}
Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
columnText.Go();
}

Related

How do I cut off one half of a PDF page?

I want to print a DHL label using a label printer.
The DHL label consists of 2 parts: The left half of the image is just info that I can keep to myself. The right part of the PDF is what should actually be printed.
I would therefore like to cut away the left part of the PDF.
I do not want to make it blank, but I really I want to cut if off.
How could I do this?
You essentially want to cut away one half of the PDF page; looking at you screenshot most likely the lower half.
Using iTextSharp 5.5.13.3 you can do that like this:
var testFile = #"new pdf1.pdf";
var resultFile = #"new pdf1-Cut.pdf";
using (PdfReader pdfReader = new PdfReader(testFile))
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, File.Create(resultFile)))
{
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
Rectangle cropBox = pdfReader.GetCropBox(i);
PdfArray newCropBox = new PdfArray(new float[] {
cropBox.Left, (cropBox.Bottom + cropBox.Top) / 2,
cropBox.Right, cropBox.Top });
PdfDictionary pageDictionary = pdfReader.GetPageN(i);
pageDictionary.Put(PdfName.CROPBOX, newCropBox);
pageDictionary.Put(PdfName.MEDIABOX, newCropBox);
}
}
(CutPages test CutInHalfForTmighty)
Before
After

Placing Text on Multiple Imported PDF Pages with iTextSharp [duplicate]

I am trying to add a header to existing pdf documents in Java with iText. I can add the header at a fixed place on the document, but all the documents are different page sizes, so it is not always at the top of the page. I have tried getting the page size so that I could calculate the position of the header, but it seems as if the page size is not actually what I want. On some documents, calling reader.getPageSize(i).getTop(20) will place the text in the right place at the top of the page, however, on some different documents it will place it half way down the page. Most of the pages have been scanned be a Xerox copier, if that makes a difference. Here is the code I am using:
PdfReader reader = new PdfReader(readFilePath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(writeFilePath));
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
PdfContentByte cb = stamper.getOverContent(i);
cb.beginText();
cb.setFontAndSize(bf, 14);
float x = reader.getPageSize(i).getWidth() / 2;
float y = reader.getPageSize(i).getTop(20);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Copy", x, y, 0);
cb.endText();
}
stamper.close();
PDF that works correctly
PDF that works incorrectly
Take a look at the StampHeader1 example. I adapted your code, introducing ColumnText.showTextAligned() and using a Phrase for the sake of simplicity (maybe you can change that part of your code too):
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Phrase header = new Phrase("Copy", new Font(FontFamily.HELVETICA, 14));
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
float x = reader.getPageSize(i).getWidth() / 2;
float y = reader.getPageSize(i).getTop(20);
ColumnText.showTextAligned(
stamper.getOverContent(i), Element.ALIGN_CENTER,
header, x, y, 0);
}
stamper.close();
reader.close();
}
As you have found out, this code assumes that no rotation was defined.
Now take a look at the StampHeader2 example. I'm using your "Wrong" file and I've added one extra line:
stamper.setRotateContents(false);
By telling the stamper not to rotate the content I'm adding, I'm adding the content using the coordinates as if the page isn't rotated. Please take a look at the result: stamped_header2.pdf. We added "Copy" at the top of the page, but as the page is rotated, we see the word appear on the side. The word is rotated because the page is rotated.
Maybe that's what you want, maybe it isn't. If it isn't, please take a look at StampHeader3 in which I calculate x and y differently, based on the rotation of the page:
if (reader.getPageRotation(i) % 180 == 0) {
x = reader.getPageSize(i).getWidth() / 2;
y = reader.getPageSize(i).getTop(20);
}
else {
x = reader.getPageSize(i).getHeight() / 2;
y = reader.getPageSize(i).getRight(20);
}
Now the word "Copy" appears on what is perceived as the "top of the page" (but in reality, it could be the side of the page): stamped_header3.pdf

iTextSharp centering text on page

I cannot get the text to be centered on the page. What am I doing wrong? I have tried several ways to get the page with, but none seem to make the text centered on the page.....
BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfReader reader = new PdfReader("C:\\temp\\Certificate12.pdf");
var pageSize = reader.GetPageSize(1);
iTextSharp.text.Rectangle rec2 = new iTextSharp.text.Rectangle(PageSize.LETTER);
PdfStamper stamper = new PdfStamper(reader, stream1);
PdfContentByte canvas = stamper.GetUnderContent(1);
canvas.BeginText();
canvas.SetFontAndSize(bf, 24);
string nameText = "First Name Last Name";
int textWidth = (int)nameText.Length;
int canvasWidth = (int)canvas.PdfDocument.PageSize.Width;
float xStart = (canvasWidth / 2) - (textWidth / 2);
canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, nameText, xStart, pageSize.GetTop(Utilities.MillimetersToPoints(145)), 0);
First of all, if you use ShowTextAligned with ALIGN_CENTER, iTextSharp will center the text for you, so you do not have to deal with the text width at all. You merely need to tell it to center the text on which center point.
Thus, you can center your text on the page like this:
BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create, FileAccess.Write)))
{
Rectangle pageSize = reader.GetPageSize(1);
PdfContentByte canvas = stamper.GetUnderContent(1);
string nameText = "First Name Last Name";
canvas.BeginText();
canvas.SetFontAndSize(bf, 24);
canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, nameText, (pageSize.Left + pageSize.Right) / 2, pageSize.GetTop(Utilities.MillimetersToPoints(145)), 0);
canvas.EndText();
}

Importing PDF position PDFStamper

I'm lost at the moment.
What I try to accomplish is adding one PDF on another (like a watermark).
The problem is that I dont seems to understand the coordinate system that is used because
my watermark just behaves unexpected.
The two PDFs have different dimensions.
My target has the following dimensions:
595 height
842 width
The PDF that shall be added has this dimension:
41 height
552 width
In my code I do the following:
public bool AddPdf(ref PdfReader pdfSource, ref PdfReader pdfTarget, ref FileStream destination)
{
PdfStamper stamper = null;
try
{
stamper = new PdfStamper( pdfSource, destination );
PdfImportedPage importatedPage = stamper.GetImportedPage(pdfTarget, 1);
PdfContentByte background;
for (int iPage = 1; iPage <= pdfSource.NumberOfPages; iPage++)
{
background = stamper.GetOverContent(iPage);
background.AddTemplate(importatedPage, 0, 0 + importHeight);
}
}
When I do this I would expect my watermark to appear in the bottom left.
Instead it is somewhere of the page (I dont see it). Just for testing I hardcoded 600 as y position and then it is centered vertically on the page.
Can someone give me a tip please?
So i solved the issue.
The problem was that the sourcepdf had a cropbox - i only needed to correct my x and y position with that information:
PdfStamper stamper = null;
try
{
stamper = new PdfStamper(pdfSource, destination);
PdfImportedPage importatedPage = stamper.GetImportedPage(pdfTarget, 1);
PdfContentByte background;
for (int iPage = 1; iPage <= pdfSource.NumberOfPages; iPage++)
{
background = stamper.GetOverContent(iPage);
// here comes the important part
Rectangle cropBox = pdfSource.GetCropBox(iPage);
float xCorrected = 0 + cropBox.Left;
float yCorrected = 0 + cropBox.Bottom;
background.AddTemplate(importatedPage, xCorrected, yCorrected);
}
}
Take in mind that in case the pdf that you want to stamp on your original has also a cropbox, you need to reduce the x,y by x,y of that cropbox again.

How to add Content to a PDF using iText PdfStamper

I'm developing a System in which I have to add some images to an existing PDF Document.
This works great with iText 5.1.3, but for some reason in a PDF that contains a scanned image it won't add any of the images.
Here's the link to the PDF Document that can't be modified with PdfStamper
and here's the code
PdfReader reader = new PdfReader("Registro celular_OR.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("DocStamped.pdf"));
Image img = Image.getInstance("someImage.jpg");
img.setAbsolutePosition(0, 0);
img.scaleAbsolute(50f, 50f);
PdfContentByte over = null;
int total = reader.getNumberOfPages() + 1;
for(int i = 1; i < total; i++) {
System.out.println("Procesando Pagina: " + i);
over = stamper.getOverContent(i);
over.addImage(img);
over.beginText();
BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
over.setFontAndSize(bf_times, 8);
over.showTextAligned(PdfContentByte.ALIGN_CENTER, "TEXTO PRUEBA", 50, 50, 0);
over.endText();
}
stamper.close();
A PDF page does not need to have its lower left corner at (0, 0). It can be anywhere in the coordinate system. So an A4 page can be (0, 0, 595, 842), but it might as well be (1000, 2000, 1595, 2842).
You are positioning the image at (0, 0):
img.setAbsolutePosition(0, 0);
But the page of this document is defined as (0, 15366, 469, 15728). The image is actually added to the output document, but it's outside the visible area of the page.
You have to get the coordinates of the page to position the image. Inside the loop, do this:
img.setAbsolutePosition(reader.getPageSize(i).getLeft(), reader.getPageSize(i).getBottom());