iText7 Create PDF in memory instead of physical file

六月ゝ 毕业季﹏ 提交于 2020-07-06 13:52:07

问题


How do one create PDF in memorystream instead of physical file using itext7? I have no idea how to do it in the latest version, any help?

I tried the following code, but pdfSM is not properly populated:

string filePath = "./abc.pdf";

MemoryStream pdfSM = new ByteArrayOutputStream();

PdfDocument doc = new PdfDocument(new PdfReader(filePath), new PdfWriter(pdfSM));
.......

doc.close();

The full testing code as below for your reference, it worked when past filePath into PdfWriter but not for the memory stream:

    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();

    }

回答1:


This works for me.

    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();
    }



回答2:


iText7、C# Controller

Error:

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

Work:

public ActionResult Report()
{
    //...
    doc1.Close();
    byte[] byte1 = memoryStream1.ToArray();
    return File(byte1, "application/pdf", "pdf_file_name.pdf");
}

I don't know why... but, it's working!

another: link



来源:https://stackoverflow.com/questions/40540741/itext7-create-pdf-in-memory-instead-of-physical-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!