【问题标题】:ItextSharp Add lines to PDF and convert into bytes without saving it.ItextSharp 将行添加到 PDF 并转换为字节而不保存。
【发布时间】:2017-11-16 17:54:20
【问题描述】:

我有一个方法可以获取 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();
    }

【问题讨论】:

  • 尝试在临时文件夹中创建文件并稍后删除?
  • 好主意!但不幸的是,这不是处理这种方法的正确方法,它只会减慢进程。另外,如果同时创建了 40 个文档,我将不得不查找该文档并删除怎么办?要删除哪个文档?

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


【解决方案1】:

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

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

【讨论】:

  • 让我试试这个和 byte[] pdf_bytes = baos.toByteArray();它应该只是 toarraay 吗?它在这个 ByteArrayOutputStream 上给出的错误不包含 tobytearray 的定义
  • 是的,请参阅我的更新。我最初用 Java 编写了 sn-p。
  • 工作谢谢!现在它不保存任何地方
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 2014-02-08
  • 2016-08-22
  • 2020-09-04
  • 1970-01-01
  • 2012-06-25
相关资源
最近更新 更多