【问题标题】:Changing PDF crop/media box using iTextSharp使用 iTextSharp 更改 PDF 裁剪/媒体框
【发布时间】:2015-09-28 07:40:57
【问题描述】:

我正在尝试使用以下代码更改现有 PDF 的媒体/裁剪框。

Document document = new Document();
FileStream outputStream = new FileStream(outFile, FileMode.Create);
PdfCopy copy = new PdfSmartCopy(document, outputStream);
document.Open();
foreach (string inFile in inFiles)
{
     PdfReader reader = new PdfReader(inFile);
     float height = Utilities.MillimetersToPoints(388);
     float width = Utilities.MillimetersToPoints(176);
     Rectangle newMedia = new Rectangle(height, width);
     copy.AddDocument(reader, new List<int> { 1 });
     copy.SetBoxSize("crop", newMedia);
     reader.Close();
}
document.Close();

我无法设置媒体框。它总是以相同的值返回。有什么我遗漏的吗?

【问题讨论】:

  • 如果您需要在PdfCopy 期间更换媒体框,您可以像在this answer 中一样进行操作。

标签: pdf itextsharp


【解决方案1】:

每个文档都有一个页面树。这是一个结构,/Pages 字典作为分支,/Page 字典作为叶子。每个页面字典(页面树中的每一片叶子)都对应一个页面。

每个页面字典都有自己的/MediaBox 条目(这是一个必需 条目)。它还可以有一个/CropBox 条目(可选,就像ArtBox/BleedBox/TrimBox)。这些条目可以被继承,因此您可以将它们添加到一个分支(/Page 所属的 /Pages 对象),但是您现有 PDF 中的每个页面都有自己的 /MediaBox,这将推翻 @ 987654332@ 在分支级别定义。

因此,我担心您将不得不更改代码,如我书中的 CropPages 示例所示:

public byte[] ManipulatePdf(byte[] src) {
  PdfReader reader = new PdfReader(src);
  int n = reader.NumberOfPages;
  PdfDictionary pageDict;
  PdfRectangle rect = new PdfRectangle(55, 76, 560, 816);
  for (int i = 1; i <= n; i++) {
    pageDict = reader.GetPageN(i);
    pageDict.Put(PdfName.CROPBOX, rect);
  }
  using (MemoryStream ms = new MemoryStream()) {
    using (PdfStamper stamper = new PdfStamper(reader, ms)) {
    }
    return ms.ToArray();
  }
}

换句话说:您必须遍历通过PdfReader 提供的所有页面,并更改每个页面字典的/CropBox(或/MediaBox)条目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2011-08-13
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多