Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText7 Create PDF in memory instead of physical file

Tags:

c#

memory

pdf

itext

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

    }
like image 417
Zhao JIN Avatar asked Nov 11 '16 03:11

Zhao JIN


2 Answers

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();
    }
like image 63
Fred Avatar answered Sep 20 '22 12:09

Fred


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

like image 42
user13055457 Avatar answered Sep 22 '22 12:09

user13055457