iText7在内存而不是物理文件中创建PDF [英] iText7 Create PDF in memory instead of physical file

查看:430
本文介绍了iText7在内存而不是物理文件中创建PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用itext7在内存流中创建PDF而不是物理文件? 我不知道如何在最新版本中进行操作,有帮助吗?

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?

我尝试了以下代码,但pdfSM的填充不正确:

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

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

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

    }

推荐答案

这对我有用.

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

这篇关于iText7在内存而不是物理文件中创建PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆