我有一个PDF,在一个页面上有一个插件控件。我需要将它与另一个pdf合并,但是当我这样做时,插件被重新压缩为一个空白矩形。有没有办法合并并保留插件控件?如果重要,该插件是从http://www.3ds.com/products/3dvia/3dvia-composer/resource-center/安装的Dessault Systemes 3D Via Composer Player控件
我正在使用的代码是简单的编写器getinstance,contentbyte directcontent,getimportedpage,addtemplate。没什么好看的。
FileStream docStream = new FileStream(@"C:\Temp\Merged.pdf", FileMode.Create);
Document newDocument = new Document(PageSize.A4.Rotate());
PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, docStream);
try
{
newDocument.Open();
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
newDocument.NewPage();
PdfReader mainPage = new PdfReader(@"C:\Temp\PageWithPlugin.pdf");
PdfImportedPage importedPage1 = pdfWriter.GetImportedPage(mainPage, 1);
pdfContentByte.AddTemplate(importedPage1, 0, 0);
mainPage.Close();
PdfReader smgPages = new PdfReader(@"C:\Temp\MorePages.pdf");
for (int page = 1; page <= smgPage.NumberOfPages; page++)
{
newDocument.NewPage();
PdfImportedPage importedPage = pdfWriter.GetImportedPage(smgPages, page);
pdfContentByte.AddTemplate(importedPage, 0, 0);
}
smgPages.Close();
}
finally
{
docStream.Flush();
if (newDocument != null)
newDocument.Close();
docStream.Close();
}
答案 0 :(得分:2)
试一试。
List<byte[]> fileList = new List<byte[]>();
using (FileStream fileSteam = File.OpenRead((@"C:\Temp\PageWithPlugin.pdf")))
{
Byte[] byteArray = new byte[fileSteam.Length];
fileSteam.Read(byteArray, 0, byteArray.Length);
fileList.Add(byteArray);
}
using (FileStream fileSteam = File.OpenRead((@"C:\Temp\MorePages.pdf")))
{
Byte[] byteArray = new byte[fileSteam.Length];
fileSteam.Read(byteArray, 0, byteArray.Length);
fileList.Add(byteArray);
}
using(MemoryStream msOutput = new MemoryStream())
{
PdfReader pdfFile = new PdfReader(fileList[0]);
Document doc = new Document();
PdfWriter pCopy = new PdfSmartCopy(doc, msOutput);
doc.Open();
for (int k = 0; k < fileList.Count; k++)
{
for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
{
pdfFile = new PdfReader(fileList[k]);
((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
pCopy.FreeReader(pdfFile);
}
}
pdfFile.Close();
pCopy.Close();
doc.Close();
fileList.Clear();
byte[] form = msOutput.ToArray();
using (FileStream fileSteam = new FileStream(@"C:\Temp\Merged.pdf", FileMode.Create))
{
fileStream.Write(form, 0, form.Length);
}
}
答案 1 :(得分:0)
不要在口中看到礼物马但是......如果其他人使用该解决方案,则k循环存在一个小问题。在第一个文档之后,numberofpages将被一个文档关闭,并且pdfReader不断被释放并重新读取每个页面,这是不必要的。我认为这是对代码部分的改进:
using (MemoryStream msOutput = new MemoryStream())
{
Document doc = new Document();
PdfWriter pCopy = new PdfCopy(doc, msOutput);
doc.Open();
for (int k = 0; k < fileList.Count; k++)
{
PdfReader pdfFile = new PdfReader(fileList[k]);
for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
{
((PdfCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
}
pCopy.FreeReader(pdfFile);
pdfFile.Close();
}
pCopy.Close();
doc.Close();
fileList.Clear();