iText7在内存中创建PDF而不是物理文件

本文关键字:文件 PDF 内存 创建 iText7 | 更新日期: 2023-09-27 18:17:18

如何在内存流中创建PDF而不是使用itext7的物理文件?我不知道在最新的版本中怎么做,有什么帮助吗?

我尝试了以下代码,但是pdfSM没有正确填充:

string filePath = "./abc.pdf";
MemoryStream pdfSM = new ByteArrayOutputStream();
PdfDocument doc = new PdfDocument(new PdfReader(filePath), new PdfWriter(pdfSM));
.......
doc.close();

完整的测试代码如下供您参考,它在将filePath传递到PdfWriter时工作,但不适用于内存流:

    public static readonly String sourceFolder = "../../FormTest/";
    public static readonly String destinationFolder = "../../Output/";
    static void Main(string[] args)
    {
        String srcFilePattern = "I-983";
        String destPattern = "I-129_2014_";
        String src = sourceFolder + srcFilePattern + ".pdf";
        String dest = destinationFolder + destPattern + "_flattened.pdf";
        MemoryStream returnSM = new MemoryStream();
        PdfDocument doc = new PdfDocument(new PdfReader(src), new PdfWriter(returnSM));
        PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, false);
        foreach (PdfFormField field in form.GetFormFields().Values) 
        {
            var fieldName = field.GetFieldName();
            var type = field.GetType();
            if (fieldName != null)
            {
                if (type.Name.Equals("PdfTextFormField"))
                {
                        field.SetValue("T");
                }
            }               
        }
        form.FlattenFields();         
        doc.Close();
    }

iText7在内存中创建PDF而不是物理文件

这对我很有用。

    public byte[] CreatePdf()
    {
        var stream = new MemoryStream();
        var writer = new PdfWriter(stream);
        var pdf = new PdfDocument(writer);
        var document = new Document(pdf);
        document.Add(new Paragraph("Hello world!"));
        document.Close();
        return stream.ToArray();
    }

我需要同样的东西。让它像这样工作:(我包含了一些提高性能的设置)

 string HtmlString = "<html><head></head><body>some content</body></html>";
 byte[] buffer;
 PdfDocument pdfDoc = null;
 using (MemoryStream memStream = new MemoryStream())
 {
     using(PdfWriter pdfWriter = new PdfWriter(memStream, wp))
     {
        pdfWriter.SetCloseStream(true);
        using (pdfDoc = new PdfDocument(pdfWriter))
        {
           ConverterProperties props = new ConverterProperties();
           pdfDoc.SetDefaultPageSize(PageSize.LETTER);
           pdfDoc.SetCloseWriter(true);
           pdfDoc.SetCloseReader(true);
           pdfDoc.SetFlushUnusedObjects(true);
           HtmlConverter.ConvertToPdf(HtmlString, pdfDoc, props));
           pdfDoc.Close();
        }
     }
     buffer = memStream.ToArray();
 }
 return buffer;

iText7, c# Controller

错误:

public ActionResult Report()
{
    //...
    doc1.Close();
    return File(memoryStream1, "application/pdf", "pdf_file_name.pdf");
}

工作:

public ActionResult Report()
{
    //...
    doc1.Close();
    byte[] byte1 = memoryStream1.ToArray();
    return File(byte1, "application/pdf", "pdf_file_name.pdf");
}
我不知道为什么……但是,它起作用了!

:链接