I am merging multiple PDFs into one PDF using Node, iTextSharp, and Edge. Everything is working until I try to delete the original PDFs. They are "in use" by WebKit. If I close NW they are released of course. I can run the same code but using a console app and the files can be deleted immediately. Any ideas?
---NW javascript---
var edge = require('edge');
var dotNetFunction = edge.func({
assemblyFile: 'E:/VisualStudio2013Projects/Edge/Edge.PDF/bin/Debug/Edge.PDF.dll',
typeName: 'Edge.PDF.StartUp',
methodName: 'MergePDF'
});
var payload = {
targetPDF: 'C:/test/042715JM75-NEW.pdf',
filesPDF: ['C:/test/042715JM75.pdf','C:/test/042715JM75-sales-copy.pdf'],
};
---C#---
namespace Edge.PDF
{
public class StartUp
{
public async Task<object> MergePDF(dynamic input)
{
return await Task.Run(async () =>
{
string lJsonData = string.Empty;
string targetPDF = input.targetPDF;
var filesPDF = input.filesPDF;
using (FileStream stream = new FileStream(targetPDF, FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A4);
PdfCopy pdf = new PdfCopy(pdfDoc, stream);
pdfDoc.Open();
var files = filesPDF;
foreach (string file in files)
{
pdf.AddDocument(new PdfReader(file));
}
if (pdfDoc != null)
pdfDoc.Close();
}
return Newtonsoft.Json.JsonConvert.SerializeObject(new { success = true});
});
}
}
}
Instead of creating an array of files (filesPDF
), you should create an array of PdfReader
instances. Add each of these readers to the pdf
and after closing the pdf
, loop over the readers once more to close them:
foreach (PdfReader reader in fileReaders) {
reader.Close();
}
Now the filehandlers will be released, and you'll be able to delete the files.