I am using the below function to split the pdf into two.
Though it is spliting the pdf, the content is appearing upside down. How do I rotate it by 180 degrees.
Please help. below is the code for the same
private static void ExtractPages(string inputFile, string outputFile,
int start, int end)
{
// get input document
PdfReader inputPdf = new PdfReader(inputFile);
// retrieve the total number of pages
int pageCount = inputPdf.NumberOfPages;
if (end < start || end > pageCount)
{
end = pageCount;
}
// load the input document
Document inputDoc =
new Document(inputPdf.GetPageSizeWithRotation(1));
// create the filestream
using (FileStream fs = new FileStream(outputFile, FileMode.Create))
{
// create the output writer
PdfWriter outputWriter = PdfWriter.GetInstance(inputDoc, fs);
inputDoc.Open();
PdfContentByte cb1 = outputWriter.DirectContent;
// copy pages from input to output document
for (int i = start; i <= end; i++)
{
inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(1));
inputDoc.NewPage();
PdfImportedPage page =
outputWriter.GetImportedPage(inputPdf, i);
int rotation = inputPdf.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb1.AddTemplate(page, 0, -1f, 1f, 0, 0,
inputPdf.GetPageSizeWithRotation(i).Height);
}
else
{
cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
inputDoc.Close();
}
}
I tried your code and it worked fine for me; split pages kept their original orientation.
A workaround might be to explicitly rotate your pages 180 degrees.
Replace:
With:
If your call to
inputPdf.GetPageRotation(i)
returns 180 then you can handle this in theif
statement that follows (using my suggested code for rotation == 180).You should try this. It worked for me:
A little change in above code old code
new code
This will fix the issue with 270 degree rotation
I have found the above answers do not rotate correctly for all 4 of the main rotations.
Below is my code to handle 0, 90, 180 and 270 correctly. This has been tested with a PDF rotated in each of these directions.
@TimS
' answer was very close to perfect, and provided the correct parameters toAddTemplate
, but I needed to make a few additions to allow for 90, 180, 270 rotation of a PDF where the pages already have rotation of 0, 90, 180 or 270:Assuming a parameter of
RotateFlipType rotateFlipType
is passed to the function to specify the rotation (the handy enum from the GDI+ RotateFlip call):Hopefully this will help someone else wishing to correct the rotation of incoming PDFs. Took me 2 days to perfect it.