creating a pdf from a template in itextsharp and outputting as content disposition.

前端 未结 2 816
忘了有多久
忘了有多久 2020-12-16 03:03

I would like to open an existing pdf, add some text and then output as content disposition using itext sharp. I have the following code. Where it falls down it is that i wan

2条回答
  •  旧巷少年郎
    2020-12-16 03:51

    The second part of your question title says:

    "outputting as content disposition"

    If that's what you really want you can do this:

    Response.AddHeader("Content-Disposition", "attachment; filename=DESIRED-FILENAME.pdf");
    

    Using a MemoryStream is unnecessary, since Response.OutputStream is available. Your example code is calling NewPage() and not trying to add the text to an existing page of your PDF, so here's one way to do what you asked:

    Response.ContentType = "application/pdf";    
    Response.AddHeader("Content-Disposition", "attachment; filename=itextTest.pdf");
    PdfReader reader = new PdfReader(readerPath);
    // store the extra text on the last (new) page
    ColumnText ct = new ColumnText(null);
    ct.AddElement(new Paragraph("Text on a new page"));
    int numberOfPages = reader.NumberOfPages;
    int newPage = numberOfPages + 1;
    // get all pages from PDF "template" so we can copy them below
    reader.SelectPages(string.Format("1-{0}", numberOfPages));
    float marginOffset = 36f;
    /*
    * we use the selected pages above with a PdfStamper to copy the original.
    * and no we don't need a MemoryStream...
    */
    using (PdfStamper stamper = new PdfStamper(reader, Response.OutputStream)) {
    // use the same page size as the __last__ template page    
      Rectangle rectangle = reader.GetPageSize(numberOfPages);
    // add a new __blank__ page      
      stamper.InsertPage(newPage, rectangle);
    // allows us to write content to the (new/added) page
      ct.Canvas = stamper.GetOverContent(newPage);
    // add text at an __absolute__ position      
      ct.SetSimpleColumn(
        marginOffset, marginOffset, 
        rectangle.Right - marginOffset, rectangle.Top - marginOffset
      );
      ct.Go();
    }
    

    I think you've already figured out that the Document / PdfWriter combination doesn't work in this situation :) That's the standard method for creating a new PDF document.

提交回复
热议问题