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

标签 c# itext

我对此进行了研究并尝试旋转单页 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();
    }
}

如有任何建议,我们将不胜感激。

最佳答案

我使用 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);

关于c# - 旋转 PDF 页面内容而不是实际页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272924/

相关文章:

java - IText 编写器返回上一页

c# - 将多种内容类型写入 Web 部件页面响应流

c# - Asp.Net MVC 路由在路由中使用 C# 关键字

c# - 在 C# .Net 中哪个命名空间包含 hWnd?

pdf - 在浏览器中显示 PDF 时,我可以隐藏 Adob​​e float 工具栏吗?

android - 如何在 Android 中使用 XMLWorkerHelper 类获得正确的 UTF-8 字符集结果?

java - 使用 PDFBox、iText 提取文本为空且未知,因为文本具有 type3 字体(困难的主题!)

c# - 为什么 volatile 还不够?

c# - Excel 文件生成器 : How to test resulting file

scala - OpenPDF/iText 损坏的文件