2013-11-28 107 views
2

我研究了这一点,并试图旋转单页PDF的内容。我可以旋转页面90,180或270度。我不想旋转页面,而是旋转内容。旋转PDF页面的内容,而不是实际的页面

这里是到目前为止,我已经适应了方法:

public static byte[] RotatePdf(byte[] fileBytes, int degreesClockwise) 
{ 
    if (degreesClockwise % 90 != 0) 
     throw new ApplicationException(string.Format("degreesClockwise must be 0, 90, 180, 360: {0}", degreesClockwise)); 

    PdfReader reader = new PdfReader(fileBytes); 
    using (var fs = new MemoryStream()) 
    { 
     PdfStamper stamper = new PdfStamper(reader, fs); 

     PdfDictionary pageDict = reader.GetPageN(1); 
     int desiredRotation = degreesClockwise; // x degrees clockwise from what it is now 
     PdfNumber rotation = pageDict.GetAsNumber(PdfName.ROTATE); 
     if (rotation != null) 
     { 
      desiredRotation += rotation.IntValue; 
      desiredRotation %= 360; // must be 0, 90, 180, or 270 
     } 
     pageDict.Put(PdfName.ROTATE, new PdfNumber(desiredRotation)); 

     stamper.Close(); 

     return fs.ToArray(); 
    } 
} 

任何建议,将不胜感激。

+0

嗯,这是怎么代码不完整?即它现在取得了什么成就?这与你想要的有何不同? – millimoose

+0

*我不想旋转页面,而是内容* - 有什么区别? – mkl

+0

@millimoose代码旋转页面方向和内容。我想要的方向保持不变,但旋转90度的内容。 – Seany84

回答

1

我使用PdfSharp库完成了代码,因为我找不到iTextSharp的任何示例或答案。

这里是我用来实现我想要的东西代码:

// Create the output document 
PdfDocument outputDocument = new PdfDocument(); 

// Show single pages 
// (Note: one page contains two pages from the source document) 
outputDocument.PageLayout = PdfPageLayout.SinglePage; 

// Open the external document as XPdfForm object 
XPdfForm form = XPdfForm.FromFile(filename); 

for (int i = 0; i < form.PageCount; i++) 
{ 
    // Add a new page to the output document 
    PdfPage page = outputDocument.AddPage(); 
    page.Orientation = PageOrientation.Landscape; 
    double width = page.Width; 
    double height = page.Height; 

    int rotate = page.Elements.GetInteger("/Rotate"); 

    XGraphics gfx = XGraphics.FromPdfPage(page); 

    XRect box = new XRect(0, 0, width, height * 2); 
    // Draw the page identified by the page number like an image 
    gfx.DrawImage(form, box); 
} 

// Save the document... 
filename = "RotatedAndStretched_tempfile.pdf"; 
outputDocument.Save(filename); 
相关问题