Is there a straight forward way to append one PDF doc to another using iTextSharp?

后端 未结 4 813
粉色の甜心
粉色の甜心 2021-02-06 04:39

I\'ve scoured the Web looking for examples on how to do this. I\'ve found a few that seem to be a little more involved then they need to be. So my question is, using iTextShar

4条回答
  •  一整个雨季
    2021-02-06 05:06

    Yes. I've seen a class called PdfManipulation posted in an iText forum. Using that class would involve a third file though.

    The class is originally in VB.Net. I downloaded it from a post on vbforums.com. Apparently though, it doesn't have the merge files function, so I wrote one based on the code in that class.

    This was written on a machine without iTextSharp. This might have bugs. I'm not even sure if page numbers are 0-based or 1-based. But give it a shot.

    public static void MergePdfFiles(IEnumerable files, string output) {
        iTextSharp.text.Document doc;
        iTextSharp.text.pdf.PdfCopy pdfCpy;
    
        doc = new iTextSharp.text.Document();
        pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(output, System.IO.FileMode.Create));
        doc.Open();
    
        foreach (string file in files) {
            // initialize a reader
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file);
            int pageCount = reader.NumberOfPages;
    
            // set page size for the documents
            doc.SetPageSize(reader.GetPageSizeWithRotation(1));
    
            for (int pageNum = 1; pageNum <= pageCount; pageNum++) {
                iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, pageNum);
                pdfCpy.AddPage(page);
            }
    
            reader.Close();
        }
    
        doc.Close();
    }
    

提交回复
热议问题