Объединить PDF-файлы - PullRequest
       26

Объединить PDF-файлы

4 голосов
/ 01 июня 2011

Возможно ли объединить заполняемый pdf-файл с обычным pdf-файлом в asp.net C # с помощью itextsharp.Любая помощь будет принята с благодарностью.

Ответы [ 4 ]

10 голосов
/ 09 июля 2011

Мне потребовалось много времени, чтобы понять это, но вот рабочий пример:

public static void MergeFiles(string destinationFile, string[] sourceFiles)
    {
        try 
        {
            int f = 0;
            String outFile = destinationFile;
            Document document = null;
            PdfCopy  writer = null;
            while (f < sourceFiles.Length) {
                // Create a reader for a certain document
                PdfReader reader = new PdfReader(sourceFiles[f]);

                // Retrieve the total number of pages
                int n = reader.NumberOfPages;
                //Trace.WriteLine("There are " + n + " pages in " + sourceFiles[f]);
                if (f == 0) 
                {
                    // Step 1: Creation of a document-object
                    document = new Document(reader.GetPageSizeWithRotation(1));
                    // Step 2: Create a writer that listens to the document
                    writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                    // Step 3: Open the document
                    document.Open();
                }
                // Step 4: Add content
                PdfImportedPage page;
                for (int i = 0; i < n; ) 
                {
                    ++i;
                    page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }
                PRAcroForm form = reader.AcroForm;
                if (form != null)
                    writer.CopyAcroForm(reader);
                f++;
            }
            // Step 5: Close the document
            document.Close();
        }
        catch(Exception) 
        {
            //handle exception
        }
    }

Надеюсь, это поможет!

Источник: http://www.ujihara.jp/iTextdotNET/examples/concat_pdf.java

0 голосов
/ 17 января 2014

Я понимаю, что это довольно старая тема, однако у меня была похожая проблема, и вот более чистое решение

public string GetMergedPdfPath(List<KeyValuePair<AccountHolder, string>> filePaths, string outputFilename)
{

string directory = ApplicationDeployment.IsNetworkDeployed ? ApplicationDeployment.CurrentDeployment.DataDirectory : NoticeConstants.Paths.TestDirectory;
string outputFilepath = directory + "\\" + outputFilename;

Document outputDocument = null;
PdfCopy outputCopier = null;

try
{
   using (outputDocument = new Document())
   {
       using (FileStream fs = new FileStream(outputFilepath, FileMode.Create))
       {
            using (outputCopier = new PdfCopy(outputDocument, fs))
            {
                outputDocument.Open();

                for (int i = 0; i < filePaths.Count; i++)
                {
                    if (string.IsNullOrEmpty(filePaths[i].Value))
                    {
                        continue;
                    }

                    using (PdfReader reader = new PdfReader(filePaths[i].Value))
                    {
                        NoticeUtil.GetPdfPages(reader, ref outputCopier);
                    }
                }

                outputDocument.Close();
            }
        }
    }

      return outputFilepath;
  }
  catch (Exception ex)
  {
      Log.Error(ex.Message, ex);

      return string.Empty;
  }

}

    private static List<PdfImportedPage> GetPdfPages(PdfReader reader, ref PdfCopy outputCopier)
    {
        List<PdfImportedPage> pages = new List<PdfImportedPage>();

        try
        {
            for (int p = 1; p <= reader.NumberOfPages; p++)
            {
                outputCopier.AddPage(outputCopier.GetImportedPage(reader, p));
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message, ex);
        }

        return pages;
    }
0 голосов
/ 26 августа 2013

Вы можете использовать PdfCopyFields для объединения любых сложных заполняемых PDF-форм.Он поддерживает все стили, поля формы и функции PDF. Просто попробуйте этот код ..

PdfReader readerfile1 = new PdfReader("File1");
PdfReader readerfile2 = new PdfReader("File2");


    PdfCopyFields copyfile =
    new PdfCopyFields(new FileStream("OutputFilewithFullPath", FileMode.Create));
    copyfile.AddDocument(readerfile1);
    copyfile.AddDocument(readerfile2);
    copyfile.Close();

Это приведет к созданию нового файла, который вы указали, и будет заполненной формой.

0 голосов
/ 02 июня 2011

Да.

PdfCopyFields звучит как раз правильно. Таким образом, даже если ваш «обычный файл PDF» содержит какие-либо аннотации (ссылки, флэш-память и т. Д.), Они все равно будут работать нормально.

В качестве альтернативы, вы можете открыть форму с помощью PdfStamper и добавить PdfImportedPages из «обычного» PDF. Это сохранит все об исходном PDF (метаданные, структуру, сценарии уровня документа и т. Д.) И будет всасывать страницы (без всего, что не было содержимым страницы) из "обычного pdf".

К сожалению, здесь нет идеального ответа, но есть как минимум два жизнеспособных варианта на выбор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...