旋转PDF页面内容而不是实际页面

时间:2013-11-28 18:40:51

标签: c# itextsharp

我研究了这个并试图旋转单页PDF的内容。我能够将页面旋转90度,180度或270度。我不想旋转页面而是内容。

这是我到目前为止所采用的方法:

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();
    }
}

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分: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);