ItextSharp将行添加到PDF并转换为字节而不保存。

时间:2017-11-16 17:54:20

标签: c# asp.net itext pdf-generation

我有一个方法可以获得pdf并在该pdf中添加行,然后创建一个新的pdf并将其保存在给定的路径中。现在我不想将新文件保存在路径中,而是想将其转换为字节并在电子邮件中发送我怎么能这样做我尝试了几种方法但是它们都寻找路径说这里找不到路径是代码。

     protected void CreatePDF()
    {

        string Oldfile = @"C:\BlankPDFt.pdf"; // Gets the Template / The actualy agreement Letter
      //  (new FileInfo("C:/Documents/Docs.pdf")).Directory.Create(); // Go create this folder if it's not there
      string NewFile = "C:/Documents/Docs.pdf";
        PdfReader reader = new PdfReader(Oldfile);
        iTextSharp.text.Rectangle Size = reader.GetPageSizeWithRotation(1);
        Document document = new Document(Size);
        FileStream fs = new FileStream(NewFile , FileMode.Create, FileAccess.Write); // This is where it all ways look for new file path
 i dont want it to save instead convert to bytes but wont work.
        PdfWriter weiter = PdfWriter.GetInstance(document, fs);
        document.Open();
        PdfContentByte cb = weiter.DirectContent;
        PdfImportedPage page = weiter.GetImportedPage(reader, 1);
        cb.AddTemplate(page, 0, 0);
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.SetColorFill(BaseColor.BLACK);
        cb.SetFontAndSize(bf, 12);
        cb.BeginText();
     //   string Signatur = "Some texts"; // adds this text to that pdf 
      cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Here", 335, 90, 0); // Insert the signature
        cb.EndText();
    }

1 个答案:

答案 0 :(得分:0)

PdfWriter.GetInstance()方法接受InputStream作为其第二个参数。不应传递FileStream,而应传递MemoryStream

MemoryStream memory_stream = new MemoryStream();
PdfWriter.GetInstance(document, memory_stream );
...
document.Close();
byte[] pdf_bytes = memory_stream.ToArray();