Changing PDF crop/media box using iTextSharp

偶尔善良 提交于 2020-01-03 05:21:08

问题


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?


回答1:


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.

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.

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

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.



来源:https://stackoverflow.com/questions/32817914/changing-pdf-crop-media-box-using-itextsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!