首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用iTextSharp合并pdf后损坏的文件

使用iTextSharp合并pdf后损坏的文件
EN

Stack Overflow用户
提问于 2017-05-15 19:26:29
回答 1查看 758关注 0票数 0

得到合并的pdf,但损坏的文件,我不能打开使用以下代码。“targetPDF”是最终合并的pdf文件,“fileNames”拥有所有的唯一pdfs。请帮帮忙。提前谢谢。

代码语言:javascript
复制
 Using (FileStream stream = new FileStream(targetPDF, FileMode.Create, FileAccess.Write))
                {

                    Document document = new Document();
                    PdfCopy pdf = new PdfCopy(document, stream);
                    if (pdf == null)
                    {
                        return;
                    }
                    document.Open();

                    foreach (string file in fileNames)
                    {
                        PdfReader reader = new PdfReader(file);
                        reader.ConsolidateNamedDestinations();

                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            PdfImportedPage page = pdf.GetImportedPage(reader, i);
                            pdf.AddPage(page);
                            //pdf.AddDocument(new PdfReader(file));
                            // pdf.AddPage(pdf.GetImportedPage(reader, 1));
                        }


                        reader.Close();
                    }
                }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-15 19:41:13

更改这一行

代码语言:javascript
复制
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);

致:

代码语言:javascript
复制
using(Document document = new Document())
{
    using(PdfCopy pdf = new PdfCopy(document, stream))
    { 
        //do staff here...
    }
}

这样,工作完成后,所有的流都会关闭,文件也不会被锁定。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43987342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档