Rotate PDF 90 Degrees in iTextSharp [duplicate] - c#

I am trying to use a PDF for stamping and need to rotate it 90 degrees to lay it on correctly? Anyone know how to do this? Can't seem to find it online.

The Rotate90Degrees example uses PdfReader to get an instance of the document then changes the /Rotate value in every page dictionary. If there is no such entry, a /Rotate entry with value 90 is added:
final PdfReader reader = new PdfReader(source);
final int pagesCount = reader.getNumberOfPages();
for (int n = 1; n <= pagesCount; n++) {
final PdfDictionary page = reader.getPageN(n);
final PdfNumber rotate = page.getAsNumber(PdfName.ROTATE);
final int rotation =
rotate == null ? 90 : (rotate.intValue() + 90) % 360;
page.put(PdfName.ROTATE, new PdfNumber(rotation));
}
Once this is done, we use a PdfStamper to persist the change:
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
This is for iText Java. For iTextSharp, porting Java to C# is easy as the terminology is identical. Change some lower cases into upper cases like this:
PdfDictionary page = reader.GetPageN(1);
page.Put(PdfName.ROTATE, new PdfNumber(90));
There's a more or less identical code snippet in the question part of this post: How to rotate PDF page with iTextSharp without causing error in ghostscript?

For C# coders:
I replaced Bruno's answer with C# code:
and yes it's working like a charm, also you can change the rotation number to 180,270, etc
PdfReader reader = new PdfReader("Source.pdf");
int pagesCount = reader.NumberOfPages;
PdfDictionary page = reader.GetPageN(1);
PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
page.Put(PdfName.ROTATE, new PdfNumber(90));
FileStream fs = new FileStream("created.pdf", FileMode.Create,
FileAccess.Write, FileShare.None);
PdfStamper stamper = new PdfStamper(reader, fs);

Related

iTextSharp PDF only Rotates Once?

I have found code online to rotate a PDF, I then use the move command to overwrite the original file. Please let me know if there is a better way of doing this too. See code below:
string source = textBox1.Text;
string filename = Path.ChangeExtension(source, null);
string destination = filename + "-rot.pdf";
Debug.WriteLine (destination);
PdfReader reader = new PdfReader(source);
int pagesCount = reader.NumberOfPages;
for (int n = 1; n <= pagesCount; n++)
{
PdfDictionary page = reader.GetPageN(n);
PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
//int rotation = rotate == null ? 90 : (rotate.intValue() + 90) % 360;
page.Put(PdfName.ROTATE, new PdfNumber(-90));
}
FileStream fs = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None);
PdfStamper stamper = new PdfStamper(reader, fs);
stamper.Close();
reader.Close();
File.Move(destination, source, true); //overwrite original with rotated and remove rotated file
However, I'm not sure I'm understanding the itextsharp pdf rotate function. If I then run the same thing again on the same pdf, it does not rotate it again. For example, if I had it set at 90, if I ran it twice I would expect the pdf to be at 180degrees to the original, but it does not work like that.
Is there a way to do this?
Thanks
Andrew
I’m guessing it’s rotating to 90 degrees and not by 90 degrees. So doing it twice (without saving and reloading perhaps) will just tell it to rotate to 90 not by 90.

PdfStamper always assuming A4 dimensions

I'm attempting to write page numbers into my PDF document with itextsharp.
I've followed the example here. This answer points me in the direction of this implementation in C#.
Now, all works fine - assuming the page orientation is A4. In my case, it's not. I'm using a landscape A3 page. Because I want to nicely position the page number, I need the dimensions of the page I'm working on.
stamper.GetOverContent().PdfDocument.PageSize seems to always return the dimensions of an A4 page.
Here's a reproducible example:
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A3.Rotate()))
{
Debug.WriteLine(doc.PageSize);
var writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
doc.Add(new Paragraph("Hello!"));
}
byte[] firstPass = ms.ToArray();
PdfReader reader = new PdfReader(firstPass);
using (var fs = new FileStream("out2.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader, fs))
{
int totalPages = reader.NumberOfPages;
for (var i = 1; i <= totalPages; i++)
{
var under = stamper.GetUnderContent(i);
var over = stamper.GetOverContent(i);
Debug.WriteLine(under.PdfDocument.PageSize);
Debug.WriteLine(over.PdfDocument.PageSize);
}
}
}
}
The output of which is:
Rectangle: 1191x842 (rot: 90 degrees)
RectangleReadOnly: 595x842 (rot: 0 degrees)
RectangleReadOnly: 595x842 (rot: 0 degrees)
How does one properly get the page size of documents with the PdfStamper?
Please note, this question is not about generating page numbers with iTextSharp. There are various workaround. This question is particularly about reading the correct dimensions of a document via PdfStamper.
I haven't got an explanation for why stamper.GetUnderContent(i).PdfDocument defaults to A4, however, the correct way to get the page size is:
var pageSize = reader.GetPageSizeWithRotation(i);
Note that this is the full page size, including margins.

iTextSharp Resize each page to fit the pagesize

I have a .pdf document which has for example 7 pages. I split this document into 7 .pdf document, so it means that each document has only one page. But mainly I need to make fit the content of pages. So delete whitespaces, margins, resize. Have you got some simple advice? I add links for images and also code for split pdf document. Thank you for your response.
INPUT:
DESIRED OUTPUT:
CODE:
public void PdfSplitDocument(string filename)
{
String path = "C:/Doc/" + filename;
String result = "d:/output/result";
PdfCopy copy;
PdfReader reader = new PdfReader(path);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
copy = new PdfCopy(document, new FileStream(result + i + ".pdf", FileMode.Create));
document.Open();
copy.AddPage(copy.GetImportedPage(reader, i));
document.Close();
}
}
Take a look at the ShowTextMargins example. It uses the TextMarginFinder class to find the margins within which text is found. In this example, taken from my book "iText in Action - Second Edition", I use this class to draw a rectangle:
public void addMarginRectangle(String src, String dest)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
TextMarginFinder finder;
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
finder = parser.processContent(i, new TextMarginFinder());
PdfContentByte cb = stamper.getOverContent(i);
cb.rectangle(finder.getLlx(), finder.getLly(),
finder.getWidth(), finder.getHeight());
cb.stroke();
}
stamper.close();
reader.close();
}
In your case, you want to crop the pages based on the rectangle. You have a finder object that allows you to get the coordinate of the lower-left corner (llx and lly) and the coordinate of the upper-right corner (urx and ury). You can use these coordinates to crop pages as is done in the CropPages example:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
int n = reader.getNumberOfPages();
PdfDictionary pageDict;
PdfRectangle rect = new PdfRectangle(llx, lly, urx, ury);
for (int i = 1; i <= n; i++) {
pageDict = reader.getPageN(i);
pageDict.put(PdfName.CROPBOX, rect);
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
Another option is to change the media box instead of the crop box:
pageDict.put(PdfName.MEDIABOX, rect);
The C# version of these examples can be found here:
ShowTextMargins
CropPages

Rotating PDF 90 degrees using iTextSharp in C#

I am trying to use a PDF for stamping and need to rotate it 90 degrees to lay it on correctly? Anyone know how to do this? Can't seem to find it online.
The Rotate90Degrees example uses PdfReader to get an instance of the document then changes the /Rotate value in every page dictionary. If there is no such entry, a /Rotate entry with value 90 is added:
final PdfReader reader = new PdfReader(source);
final int pagesCount = reader.getNumberOfPages();
for (int n = 1; n <= pagesCount; n++) {
final PdfDictionary page = reader.getPageN(n);
final PdfNumber rotate = page.getAsNumber(PdfName.ROTATE);
final int rotation =
rotate == null ? 90 : (rotate.intValue() + 90) % 360;
page.put(PdfName.ROTATE, new PdfNumber(rotation));
}
Once this is done, we use a PdfStamper to persist the change:
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
This is for iText Java. For iTextSharp, porting Java to C# is easy as the terminology is identical. Change some lower cases into upper cases like this:
PdfDictionary page = reader.GetPageN(1);
page.Put(PdfName.ROTATE, new PdfNumber(90));
There's a more or less identical code snippet in the question part of this post: How to rotate PDF page with iTextSharp without causing error in ghostscript?
For C# coders:
I replaced Bruno's answer with C# code:
and yes it's working like a charm, also you can change the rotation number to 180,270, etc
PdfReader reader = new PdfReader("Source.pdf");
int pagesCount = reader.NumberOfPages;
PdfDictionary page = reader.GetPageN(1);
PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
page.Put(PdfName.ROTATE, new PdfNumber(90));
FileStream fs = new FileStream("created.pdf", FileMode.Create,
FileAccess.Write, FileShare.None);
PdfStamper stamper = new PdfStamper(reader, fs);

Divide one page PDF file in two pages PDF file

I'm using iTextSharp to handle pdf files. I'd like to know how I can split a page in half and make 2 different pages from the two pieces. I tried a lot but nothing seems to work right now.
First try
iTextSharp.text.Rectangle size = new iTextSharp.text.Rectangle(0, pdfReader.GetPageSize(1).Height / 2, pdfReader.GetPageSize(1).Width, 0);
Second try
iTextSharp.text.Rectangle size = pdfReader.GetPageSizeWithRotation(1);
iTextSharp.text.Document document = new iTextSharp.text.Document(size.GetRectangle(0, size.Height / 2));
And several others. The results are always the same: I have a file with just the second half of the original page.
I don't understand your code snippets, but then again: probably you don't understand them either, so let's not look at what you've written so far, and let's take a closer look at the TileInTwo example:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
// Creating a reader
PdfReader reader = new PdfReader(src);
int n = reader.getNumberOfPages();
// step 1
Rectangle mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(1)));
Document document = new Document(mediabox);
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3
document.open();
// step 4
PdfContentByte content = writer.getDirectContent();
PdfImportedPage page;
int i = 1;
while (true) {
page = writer.getImportedPage(reader, i);
content.addTemplate(page, 0, -mediabox.getHeight());
document.newPage();
content.addTemplate(page, 0, 0);
if (++i > n)
break;
mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(i)));
document.setPageSize(mediabox);
document.newPage();
}
// step 5
document.close();
reader.close();
}
public Rectangle getHalfPageSize(Rectangle pagesize) {
float width = pagesize.getWidth();
float height = pagesize.getHeight();
return new Rectangle(width, height / 2);
}
In this example, we ask the PdfReader instance for the page size of the first page and we create a new rectangle with the same width and only half the height.
We then import each page in the document, and we add it twice on different pages:
once on the odd pages with a negative y value to show the upper half of the original page,
once on the even pages with y = 0 to show the lower half of the original page.
As every page in the original document can have a different size, we may need to change the page size for every new couple of pages.

Categories