Rotating PDF in C# using iTextSharp

后端 未结 5 1178
野的像风
野的像风 2020-12-08 17:04

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.

5条回答
  •  旧巷少年郎
    2020-12-08 17:23

    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.

    var pageRotation = reader.GetPageRotation(currentPageIndex);
    var pageWidth = reader.GetPageSizeWithRotation(currentPageIndex).Width;
    var pageHeight = reader.GetPageSizeWithRotation(currentPageIndex).Height;
    switch (pageRotation)
    {
        case 0:
            writer.DirectContent.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
            break;
    
        case 90:
            writer.DirectContent.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pageHeight);
            break;
    
        case 180:
            writer.DirectContent.AddTemplate(importedPage, -1f, 0, 0, -1f, pageWidth, pageHeight);
            break;
    
        case 270:
            writer.DirectContent.AddTemplate(importedPage, 0, 1f, -1f, 0, pageWidth, 0);
            break;
    
        default:
            throw new InvalidOperationException(string.Format("Unexpected page rotation: [{0}].", pageRotation));
    }
    

提交回复
热议问题