将PDF与ITextSharp合并

时间:2010-02-09 22:52:09

标签: pdf merge itextsharp

在C#中将2个PDF文件与ITextSharp合并的最佳方法是什么?我正在使用ASP.NET /.NET3.5。

2 个答案:

答案 0 :(得分:27)

public static 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;

            //fixed typo
            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();
            });
        }
    }

答案 1 :(得分:1)

如果您不想删除原始文件,则最后一个答案有效。在我的情况下,我想删除,当我尝试时,我得到了例外。我的解决方案是:

  public static bool MergePDFs(List<String> InFiles, String OutFile)
        {
            bool merged = true;
            try
            {
                List<PdfReader> readerList = new List<PdfReader>();
                foreach (string filePath in InFiles)
                {
                    PdfReader pdfReader = new PdfReader(filePath);
                    readerList.Add(pdfReader);
                }

                //Define a new output document and its size, type
                Document document = new Document(PageSize.A4, 0, 0, 0, 0);
                //Create blank output pdf file and get the stream to write on it.
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OutFile, FileMode.Create));
                document.Open();

                foreach (PdfReader reader in readerList)
                {
                    PdfReader.unethicalreading = true;
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        document.Add(iTextSharp.text.Image.GetInstance(page));
                    }
                }
                document.Close();
                foreach (PdfReader reader in readerList)
                {
                    reader.Close();
                }

            }
            catch (Exception ex)
            {
                merged = false;
            }


            return merged;
        }

我从Original Code

复制了代码