使用textsharp抓取PDF的所有页面

时间:2017-12-11 17:49:54

标签: c# asp.net pdf itext

我正在使用旧版本的itextsharp和这段代码获得一个pfd

string Oldfile = @"C:/test.pdf"; // Gets the Template 
    (new FileInfo("C:/C:/test.pdf")).Directory.Create(); // Go create this folder if it's not there
    string NewFile = "C:/test.pdf";
    PdfReader reader = new PdfReader(Oldfile);
    iTextSharp.text.Rectangle Size = reader.GetPageSizeWithRotation(1);
    Document document = new Document(Size);
 //   MemoryStream memory_stream = new MemoryStream();
   FileStream fs = new FileStream(NewFile, FileMode.Create, FileAccess.Write);
    PdfWriter weiter = PdfWriter.GetInstance(document, fs);
    document.Open();
    PdfContentByte cb = weiter.DirectContent;
    PdfImportedPage page = weiter.GetImportedPage(reader, 1);
    //PdfImportedPage page2 = weiter.GetImportedPage(reader, 2);
    cb.AddTemplate(page, 0, 0);

我遇到的问题是当它获得该文件时它在该pdf中有2个页面,但它只获得第1页并添加行并保存pdf的唯一第一页我希望能够抓住它们或者是否存在一种在病房后合并它们的方法

1 个答案:

答案 0 :(得分:0)

我打赌你需要迭代所有页面。

using System;
using System.IO;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace TestAnything
{
    class Program
    {

        static void Main(string[] args)
        {
            List<string> filesToMerge = new List<string> { @"c:\temp\1.pdf", @"c:\temp\2.pdf" };
            FileInfo destinationFile = new FileInfo(@"c:\temp\merge.pdf");
            if (File.Exists(destinationFile.FullName))
                File.Delete(destinationFile.FullName);
            MergeFiles(filesToMerge, destinationFile);
        }


        public static void MergeFiles(List<string> sourceFiles, FileInfo destinationFile)
        {
            if (sourceFiles == null || sourceFiles.Count == 0)
                throw new ArgumentNullException("blahhh.");

            PdfReader reader = new PdfReader(sourceFiles[0]);
            Document document = new Document(reader.GetPageSizeWithRotation(1));
            PdfCopy writer = new PdfCopy(document, new FileStream(destinationFile.FullName, FileMode.Create));
            document.Open();
            try
            {
                foreach (string sourceFile in sourceFiles)
                {
                    reader = new PdfReader(sourceFile);
                    reader.ConsolidateNamedDestinations();

                    for (int x = 1; x <= reader.NumberOfPages; x++)
                        writer.AddPage(writer.GetImportedPage(reader, x));

                    PRAcroForm form = reader.AcroForm;
                    if (form != null)
                        writer.CopyAcroForm(reader);
                }
            }
            finally
            {
                if (document.IsOpen())
                    document.Close();
            }
        }
    }
}