使用iTextSharp合并PDF会删除修剪框细节

时间:2015-09-11 02:03:23

标签: pdf merge itextsharp

我正在尝试使用iTextSharp合并2个或更多PDF文件。但是我没有得到有关TrimBox的任何细节。在PDF上执行以下代码(已合并)始终返回NULL

Rectangle rect = reader.GetBoxSize(1, "trim");

这是合并的代码。

public void Merge(List<String> InFiles, String OutFile)
        {
            using (FileStream stream = new FileStream(OutFile, FileMode.Create))
            using (Document doc = new Document())
            using (PdfCopy pdf = new PdfCopy(doc, stream))
            {
                doc.Open();

                PdfReader reader = null;
                PdfImportedPage page = null;

                InFiles.ForEach(file =>
                {
                    reader = new PdfReader(file);

                    for (int i = 0; i < reader.NumberOfPages; i++)
                    {
                         page = pdf.GetImportedPage(reader, i + 1);
                         pdf.AddPage(page);
                    }


                    pdf.FreeReader(reader);
                    reader.Close();
                });
            }
        }

合并后如何保留箱子信息?

-Alan -

1 个答案:

答案 0 :(得分:0)

以下是我使用iTextSharp合并Portrait和Landscape文档时创建的代码。它工作得很好。

public void MergeFiles(System.Collections.Generic.List<string> sourceFiles, string destinationFile)
{
    Document document=null;
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);
    try
    {
        PdfCopy writer = null;    
        int numberOfPages=0;
        foreach(string sourceFile in sourceFiles)
        {                    
            PdfReader reader = new PdfReader(sourceFile);
            reader.ConsolidateNamedDestinations();                 
            numberOfPages = reader.NumberOfPages; 

            if(document==null)
            {
                document = new Document(reader.GetPageSizeWithRotation(1));
                writer = new PdfCopy(document, new FileStream(destinationFile, FileMode.Create));                      
                    document.Open();
            }
            for (int x = 1;x <= numberOfPages;x++ )
            {                     
                if (writer != null)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, x);
                    writer.AddPage(page);
                }
            }
            PRAcroForm form = reader.AcroForm;
            if (form != null && writer != null)                    
                writer.CopyAcroForm(reader);                                       
        }                
    }
    finally
    {
        if (document != null && document.IsOpen())
            document.Close();
    }
}