Last active
January 6, 2023 21:46
-
-
Save icalderond/29ec3e1eaaba9b2c776d to your computer and use it in GitHub Desktop.
Unir pdf con iTextSharp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Une dos PDF uno detras del otro dependiendo de como los va encontrando | |
/// </summary> | |
/// <param name="targetPDF">La ruta completa del archivo .PDF que se va a crear</param> | |
/// <param name="sourceDir">La ruta del folder que contiene los .PDF a unir</param> | |
public void CreateMergedPDF(string targetPDF, string sourceDir) | |
{ | |
using (FileStream stream = new FileStream(targetPDF, FileMode.Create)) | |
{ | |
Document pdfDoc = new Document(PageSize.A4); | |
PdfCopy pdf = new PdfCopy(pdfDoc, stream); | |
pdfDoc.Open(); | |
var files = Directory.GetFiles(sourceDir); | |
foreach (string file in files) | |
{ | |
if (file.Split('.').Last().ToUpper() == "PDF") | |
{ | |
pdf.AddDocument(new PdfReader(file)); | |
} | |
} | |
if (pdfDoc != null) | |
pdfDoc.Close(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Private Sub CreateMergedPDF(targetPDF As String, sourceDir As String) | |
Dim stream As New FileStream(targetPDF, FileMode.Create) | |
Dim pdfDoc = New Document(PageSize.A4) | |
Dim pdf = New PdfCopy(pdfDoc, stream) | |
pdfDoc.Open() | |
Dim files = Directory.GetFiles(sourceDir) | |
For Each file As String In files | |
Dim list As String() | |
list = file.Split(".") | |
If list.Last().ToUpper() = "PDF" Then | |
pdf.AddDocument(New PdfReader(file)) | |
End If | |
Next | |
If pdfDoc IsNot Nothing Then | |
pdfDoc.Close() | |
End If | |
End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Debes utilizar una condicional que valide si exite un archivo en "x" ruta. Por ejemplo: if(File.Exist(ruta)){ File.Delete(ruta); }
Utiliza el método Dispose(). Así ya no estarán los archivos en uso. Por lo que podrás manipularlos tanto como quieras.
Espero haberte ayudado!