1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;
namespace DotnetFinder
{
class MergePDF
{
private BaseFont baseFont;
private bool enablePagination = false;
private readonly List<PdfReader> documents;
private int totalPages;
public BaseFont BaseFont
{
get { return baseFont; }
set { baseFont = value; }
}
public bool EnablePagination
{
get { return enablePagination; }
set
{
enablePagination = value;
if (value && baseFont == null)
baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
}
}
public List<PdfReader> Documents
{
get { return documents; }
}
public void AddDocument(string filename)
{
documents.Add(new PdfReader(filename));
}
public void AddDocument(Stream pdfStream)
{
documents.Add(new PdfReader(pdfStream));
}
public void AddDocument(byte[] pdfContents)
{
documents.Add(new PdfReader(pdfContents));
}
public void AddDocument(PdfReader pdfDocument)
{
documents.Add(pdfDocument);
}
public void Merge(string outputFilename)
{
Merge(new FileStream(outputFilename, FileMode.Create));
}
public void Merge(Stream outputStream)
{
if (outputStream == null || !outputStream.CanWrite)
throw new Exception("OutputStream es nulo o no se puede escribir en éste.");
Document newDocument = null;
try
{
newDocument = new Document();
PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, outputStream);
newDocument.Open();
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
if (EnablePagination)
documents.ForEach(delegate(PdfReader doc)
{
totalPages += doc.NumberOfPages;
});
int currentPage = 1;
foreach (PdfReader pdfReader in documents)
{
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
newDocument.NewPage();
PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page);
pdfContentByte.AddTemplate(importedPage, 0, 0);
if (EnablePagination)
{
pdfContentByte.BeginText();
pdfContentByte.SetFontAndSize(baseFont, 9);
pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
string.Format("{0} de {1}", currentPage++, totalPages), 520, 5, 0);
pdfContentByte.EndText();
}
}
}
}
finally
{
outputStream.Flush();
if (newDocument != null)
newDocument.Close();
outputStream.Close();
}
}
public MergePDF()
{
documents = new List<PdfReader>();
}
}
} |
Partager