[英]Corrupted file after merging pdf using iTextSharp
Getting merged pdf but corrupted file that I can't open using the below code. 获取合并的pdf但损坏的文件,无法使用以下代码打开。 The 'targetPDF' is the final merged pdf file and 'fileNames' has all the single pdfs.
“ targetPDF”是最终合并的pdf文件,“ fileNames”具有所有单个pdf。 Please help.
请帮忙。 Thanks in advance.
提前致谢。
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();
}
}
Change this lines 更改此行
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);
To : 至 :
using(Document document = new Document())
{
using(PdfCopy pdf = new PdfCopy(document, stream))
{
//do staff here...
}
}
So that after the work is done all streams close and files were not locked. 这样,工作完成后,所有流都将关闭,并且文件不会被锁定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.