ITextSharp从5.3.3.0升级到5.5.0.0合并文件问题-文件关闭时已经关闭
本文关键字:文件 合并 0升 ITextSharp 问题 | 更新日期: 2023-09-27 17:51:24
我的代码:
public static byte[] MergePdf(List<byte[]> pdfs, float scaleFactor)
{
int n=0;
//Removes the null pdf documents from the list
while(n < pdfs.Count)
{
if (pdfs[n] != null)
n++;
else
pdfs.RemoveAt(n);
}
if (pdfs.Count == 0)
return null;
// Create the output document
MemoryStream outputStream = new MemoryStream();
Document outputDocument = new Document();
try
{
PdfWriter writer = PdfWriter.GetInstance(outputDocument, outputStream);
outputDocument.Open();
foreach (byte[] singlePdf in pdfs)
{
PdfReader inputReader = null;
// Open the input files
inputReader = new PdfReader(singlePdf);
for (int idx = 1; idx <= inputReader.NumberOfPages; idx++)
{
Rectangle size = inputReader.GetPageSizeWithRotation(idx);
outputDocument.SetPageSize(size);
outputDocument.NewPage();
PdfImportedPage page = writer.GetImportedPage(inputReader, idx);
int rotation = inputReader.GetPageRotation(idx);
switch (rotation)
{
case 90:
throw new Exception("unsupported");
//writer.DirectContent.AddTemplate(page, scaleFactor, -1, 1, 0, scaleFactor, inputReader.GetPageSizeWithRotation(idx).Height * scaleFactor);
//break;
case 270:
throw new Exception("unsupported");
//writer.DirectContent.AddTemplate(page, scaleFactor, 1, -1, scaleFactor, inputReader.GetPageSizeWithRotation(idx).Width * scaleFactor, 0);
//break;
default:
writer.DirectContent.AddTemplate(page, scaleFactor, 0, 0, scaleFactor, (inputReader.GetPageSizeWithRotation(idx).Width - inputReader.GetPageSizeWithRotation(idx).Width * scaleFactor) / 2, (inputReader.GetPageSizeWithRotation(idx).Height - inputReader.GetPageSizeWithRotation(idx).Height * scaleFactor) / 2);
break;
}
}
inputReader.Close();
}
// Save the document and close objects
writer.CloseStream = false;
outputDocument.CloseDocument();
outputStream.Flush();
byte[] res = outputStream.ToArray();
outputStream.Close();
outputStream.Dispose();
return res;
}
catch
{
if (outputDocument.IsOpen())
outputDocument.Close();
if (outputStream != null)
{
outputStream.Close();
outputStream.Dispose();
}
throw;
}
}
我正在升级到ItextSharp 5.5.0.0版本,但我在行代码outputDocument.CloseDocument()
中获得InvalidOperationException异常消息"已关闭"。
我认为这是与inputReader.Close()
方法有关的东西,因为当我在pdf列表中只有一个元素并且我在这段代码之前移动文档时,我没有得到例外。
很明显,同样的代码在之前的版本5.3.3.0上可以完美地工作。
任何想法?由于
似乎5.4.4引入了许多对库的更改。如果可以不使用scaleFactor,下面的代码应该可以工作:
public static byte[] MergePDFs(byte[][] sourceFiles) {
using (var dest = new System.IO.MemoryStream())
using (var document = new iTextSharp.text.Document())
using (var writer = new iTextSharp.text.pdf.PdfCopy(document, dest)) {
document.Open();
foreach (var pdf in sourceFiles) {
using (var r = new iTextSharp.text.pdf.PdfReader(pdf))
writer.AddDocument(r);
}
document.Close();
return dest.ToArray();
}
}