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

后端 未结 4 821
粉色の甜心
粉色の甜心 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:26

    Ok, It's not straight forward, but it works and is surprisingly fast. (And it uses a 3rd file, no such thing as open and append.) I 'discovered' this in the docs/examples. Here's the code:

    private void CombineMultiplePDFs( string[] fileNames, string outFile ) {
        int pageOffset = 0;
        ArrayList master = new ArrayList();
        int f = 0;
    
        Document document = null;
        PdfCopy writer = null;
        while ( f < fileNames.Length ) {
            // we create a reader for a certain document
            PdfReader reader = new PdfReader( fileNames[ f ] );
            reader.ConsolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.NumberOfPages;
            ArrayList bookmarks = SimpleBookmark.GetBookmark( reader );
            if ( bookmarks != null ) {
                if ( pageOffset != 0 ) {
                    SimpleBookmark.ShiftPageNumbers( bookmarks, pageOffset, null );
                }
                master.AddRange( bookmarks );
            }
            pageOffset += n;
    
            if ( f == 0 ) {
                // step 1: creation of a document-object
                document = new Document( reader.GetPageSizeWithRotation( 1 ) );
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy( document, new FileStream( outFile, FileMode.Create ) );
                // step 3: we open the document
                document.Open();
            }
            // step 4: we add content
            for ( int i = 0; i < n; ) {
                ++i;
                if ( writer != null ) {
                    PdfImportedPage page = writer.GetImportedPage( reader, i );
                    writer.AddPage( page );
                }
            }
            PRAcroForm form = reader.AcroForm;
            if ( form != null && writer != null ) {
                writer.CopyAcroForm( reader );
            }
            f++;
        }
        if ( master.Count > 0 && writer != null ) {
            writer.Outlines = master;
        }
        // step 5: we close the document
        if ( document != null ) {
            document.Close();
        }
    }
    

提交回复
热议问题