Skip to content

Instantly share code, notes, and snippets.

@janosorcsik
Last active December 11, 2017 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janosorcsik/cb9aa7be9c03f9da0799 to your computer and use it in GitHub Desktop.
Save janosorcsik/cb9aa7be9c03f9da0799 to your computer and use it in GitHub Desktop.
Merge PDFs
namespace CrystalPrinter.Utilities
{
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
// http://www.codeproject.com/Articles/28283/Simple-NET-PDF-Merger
public static class PDFMerger
{
/// <summary>
/// Merge pdf files.
/// </summary>
/// <param name="sourceFiles">PDF files being merged.</param>
/// <returns></returns>
public static byte[] MergeFiles(List<byte[]> sourceFiles)
{
var document = new Document();
var output = new MemoryStream();
try
{
// Initialize pdf writer
var writer = PdfWriter.GetInstance(document, output);
// Open document to write
document.Open();
var content = writer.DirectContent;
// Iterate through all pdf documents
foreach (var file in sourceFiles)
{
// Create pdf reader
var reader = new PdfReader(file);
var numberOfPages = reader.NumberOfPages;
// Iterate through all pages
for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
{
// Determine page size for the current page
document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex));
// Create page
document.NewPage();
var importedPage = writer.GetImportedPage(reader, currentPageIndex);
// Determine page orientation
var pageOrientation = reader.GetPageRotation(currentPageIndex);
if ((pageOrientation == 90) || (pageOrientation == 270))
{
content.AddTemplate(importedPage, 0F, -1F, 1F, 0F, 0F,
reader.GetPageSizeWithRotation(currentPageIndex).Height);
}
else
{
content.AddTemplate(importedPage, 1F, 0F, 0F, 1F, 0F, 0F);
}
}
}
}
catch (Exception exception)
{
throw new Exception("Hiba történt a pdf fájlok összefésülése közben", exception);
}
finally
{
document.Close();
}
return output.GetBuffer();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment