Files
UtilitatPdf/UtilitatPdf/PdfMergeFiles.cs

112 lines
3.2 KiB
C#

using System;
using System.Collections.ObjectModel;
using System.IO;
using iText.Kernel.Pdf;
using iText.Kernel.Utils;
namespace UtilitatPdf
{
public class PdfMergeFiles
{
private PdfDocument _pdfDocument = null;
private PdfDocument _pdfDocument2 = null;
private PdfMerger _pdfMerger = null;
private static string tmpFolder = System.IO.Path.GetTempPath();
private string _oldtmpFile = string.Empty;
private string _tmpFile = string.Empty;
private string _tmpFile2 = string.Empty;
private bool _mergeOK = false;
private string _FinalPdfFile = string.Empty;
public PdfMergeFiles(string FinalPdfFile, bool DeleteIfExists = true)
{
if (string.IsNullOrEmpty(FinalPdfFile))
{
throw new Exception();
}
else
{
_FinalPdfFile = FinalPdfFile;
if (DeleteIfExists)
{
if (new FileInfo(_FinalPdfFile).Exists) File.Delete(_FinalPdfFile);
}
}
}
public bool AddFiles(ObservableCollection<PdfInfo> sourceFiles)
{
foreach (PdfInfo fitxer in sourceFiles)
{
if (!this.AddFile(fitxer.FileName))
{
return false;
}
}
return true;
}
public bool AddFile(string PdfFilename)
{
checkVars(PdfFilename);
if (_mergeOK)
{
Random numr = new Random();
_oldtmpFile = tmpFolder + numr.Next(1, 99999).ToString() + "tmpfile.pdf";
try
{
_pdfDocument = new PdfDocument(new PdfReader(_tmpFile), new PdfWriter(_oldtmpFile), new StampingProperties().UseAppendMode());
_pdfDocument2 = new PdfDocument(new PdfReader(_tmpFile2));
_pdfMerger = new PdfMerger(_pdfDocument);
_pdfMerger.Merge(_pdfDocument2, 1, _pdfDocument2.GetNumberOfPages());
this.ClosePdfDocs();
}
catch (IOException)
{
throw new IOException();
}
catch(Exception)
{
throw new Exception();
}
finally
{
_tmpFile = _oldtmpFile;
_tmpFile2 = string.Empty;
_oldtmpFile = string.Empty;
_mergeOK = false;
}
}
return true;
}
public void Generate()
{
File.Copy(_tmpFile, _FinalPdfFile);
}
private void ClosePdfDocs()
{
_pdfDocument?.Close();
_pdfDocument2?.Close();
_pdfMerger?.Close();
}
private void checkVars(string file)
{
if (string.IsNullOrEmpty(_tmpFile))
{
_tmpFile = file;
}
else
{
_tmpFile2 = file;
}
if (!string.IsNullOrEmpty(_tmpFile) && !string.IsNullOrEmpty(_tmpFile2)) _mergeOK = true;
}
}
}