使用iTextSharp更改PDF裁剪/媒体框 [英] Changing PDF crop/media box using iTextSharp

查看:629
本文介绍了使用iTextSharp更改PDF裁剪/媒体框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to to change the media/crop box of an existing PDF using the code below.

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

我无法设置媒体框。它总是以相同的价值回归。我缺少的任何东西?

I am not able to set the media box. It always come back with the same value. Anything that I am missing?

推荐答案

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

Each document has a page tree. This is a structure with /Pages dictionaries as branches and /Page dictionaries as leaves. Every page dictionary (every leaf in the page tree) corresponds with a page.

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

Each page dictionary has its own /MediaBox entry (it's a required entry). It can also have a /CropBox entry (optional, just like ArtBox, /BleedBox and /TrimBox). These entries can be inherited, so you could add them to a branch (a /Pages object to which the /Page belongs), but chances are that each page in your existing PDF has its own /MediaBox which will overrule the /MediaBox defined at the branch level.

因此,我担心您必须更改代码,如 CropPages 示例:

Hence, I fear that you'll have to change your code as shown in the CropPages example from my book:

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 )每个页面词典的输入。

In other words: you have to loop over all the pages available through PdfReader and change the /CropBox (or /MediaBox) entry of every page dictionary.

这篇关于使用iTextSharp更改PDF裁剪/媒体框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆