简体   繁体   English

使用iTextSharp将PDF附加到生成的PDF

[英]Appending PDFs to generated PDF using iTextSharp

I am generating a pdf using iTextSharp. 我正在使用iTextSharp生成pdf。 If certain properties are true then I also want to insert an existing pdf with static content. 如果某些属性为true,那么我还想插入具有静态内容的现有pdf。

private byte[] GeneratePdf(DraftOrder draftOrder)

  // create a pdf document
  var document = new Document();

  // set the page size, set the orientation
  document.SetPageSize(PageSize.A4);

  // create a writer instance
  var pdfWriter = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create));

  document.Open();

  if(draftOrder.hasProperty){
    //add these things to the pdf
    var textToBeAdded = "<table><tr>....</table>";
  }
  FormatHtml(document, textToBeAdded , css);

  if(someOtherProperty){
    //add static pdf from file
    document.NewPage();

    var reader = new PdfReader("myPath/existing.pdf");
    PdfImportedPage page;

    for(var i = 0; i < reader.NumberOfPages; i++){
      //It's this bit I don't really understand
      //**how can I add the page read to the document being created?**
    }

I can load the pdf from the source but when I iterate over the pages I can't seem to be able to add them to the document I am creating. 我可以从源代码加载pdf,但是当我遍历页面时,似乎无法将它们添加到正在创建的文档中。

Cheers 干杯

Please read http://manning.com/lowagie2/samplechapter6.pdf 请阅读http://manning.com/lowagie2/samplechapter6.pdf

If you don't mind losing all interactivity, you can get the template from the writer object with the GetImportedPage() method and add it to the document with AddTemplate () . 如果你不介意失去所有的交互性,你可以从与作家对象模板GetImportedPage()方法,它用添加到文档AddTemplate ()

This question has been answered many times on StackOverflow and you'll notice that I always warn about some dangers: you need to realize that the dimensions of the imported page can be different from the page size you initially defined. 这个问题在StackOverflow上已经回答了很多次,您会注意到我总是警告某些危险:您需要意识到导入页面的尺寸可能与最初定义的页面尺寸不同。 Because of this invisible parts of the imported page can become visible; 因此,导入页面的不可见部分可以变得可见; visible parts can become invisible. 可见部分可能会变得不可见。

I'd prefer adding the extra page in a second ho using PdfCopy , but maybe that's just me. 我更喜欢使用PdfCopy在第二个步骤中添加额外的页面,但这也许就是我自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM