How to save one pdf in different places - c#

I create a pdf file using pdfstamper and I want to save my pdf in two different files (change the path in the pdfStamper) do I need to create a new pdfStamper or is there a way to save in multiple places the same file
// that's my code
PdfStamper stamper = new PdfStamper(rdr, new System.IO.FileStream(path, System.IO.FileMode.Create));

If I understand you correctly - you need to put the same file in different places, right? It seems to me the most logical thing is to perform all the necessary operations on one pdf-file and then make a copy of it using method System.IO.File.Copy(path, new_path);

Related

Copying the whole content of the PDF File to the temporary file?

Basically, I did ask already a question regarding on how to edit PDF File. But it seems that I need to pay a lot of money to achieve what I want. But here is the problem first,
I have a PDF Template containing a plain text like this {{Fullname}} like a placeholder and should be replaced with a certain value. Now, as I've said earlier, Editing the PDF File is a mess and tough because if it's not, I already saw a solution online for free.
Now, here is my Idea, What if I get the whole content of this template file and replace the placeholder with a certain value then create a new PDF File with the same content but the placeholder is already replaced?
I am trying to figure out this problem and here is my solution:
string destinationFile = Path.GetTempFileName();
string text = File.ReadAllText(sourceFile);
text = text.Replace("{{Fullname}}", "John Doe");
// Create a new PDF document
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
// Add the text to the document
document.Add(new Paragraph(text));
// Close the document
document.Close();
Currently, I am using iTextSharp and does not meet what I expected. So, my question is, Is it possible to get all the content of the PDF File and modify it to create a new one? If yes, How?

iText7 Merge of Multiple PDF MemoryStreams Not Working

I am trying to Generate a Single PDF File From Multiple Memory Streams, I am having a lot of trouble determining the proper way to merge 2 PDF MemoryStreams into one PDF MemoryStream that contains all the pages from both source PDF MemoryStreams. It seems simple and I think the code below is set up properly but the resulting PDF memory stream does not contain both the Files Combined.
I am having a lot of trouble determining the proper way to merge 2 PDF MemoryStreams into one PDF MemoryStream that contains all the pages from both source PDF MemoryStreams. It seems simple and I think the code below is set up properly but the resulting PDF memory stream does not Contain Merged Documents.
I have found multiple ways documented on the Internet as the "proper" way to do the merge. The actual sample code with iText 7 seems to be unusually complex (in that is mixes multiple concepts into one sample repeatedly - as in doesn't reduce the concept to the simplest possible code), and seems to fail to demonstrate simple concepts. For instance, their PDFMerge documentation has no sample code at all in the documentation (nor does anything else I looked at in the class documentation). The examples they have online actually always mix merging from files (not MemoryStreams or byte[]) with other concepts like adding page numbers or adding Table of Contents. So they never just show one concept and they never start with anything other than files. My PDFs are coming out of a database and we just need to merge them into one PDF memory stream and save it back out. My concern is that maybe I am not creating the MemoryStream properly when I initialize the PDFWriter. As none of their samples ever do anything but initial with an actual file, I was unable to confirm this was done properly. I also fully qualified all objects in the code because I want to leave the old iTextSharp code in place while I am upgrading to the new iText 7. This was done to make sure an iTextSharp object of the same name wasn't inadvertently being unknowingly used.
Also, in the interest of making the source as easy as possible to read I removed some of the declarations and initialization of objects being used. Everything was traced through and all values are fully loaded with proper values as you trace through the code. I am assuming the problem is that I didn't prepare the PDF objects properly or that I have to do something special with the PDFWriter on the Destination PDF Document (ms) before the the PDFMerge object.
List<byte[]> streams = new List<byte[]>();
somelist.ForEach(item=>
{
using (var workStream = new MemoryStream())
using (var pdfWriter = new PdfWriter(workStream))
{
pdfWriter.SetCloseStream(false);
HtmlConverter.ConvertToPdf(strContent, pdfWriter);
streams.Add(workStream.ToArray());
pdfWriter.Close();
}
}
MemoryStream ms = new MemoryStream();
PdfWriter writer = new PdfWriter(ms);
PdfDocument document = new PdfDocument(writer);
PdfMerger merger = new PdfMerger(document);
streams.ForEach(stream =>
{
Stream msDoc = new MemoryStream(stream);
PdfDocument doc = new PdfDocument(new PdfReader(msDoc));
merger.Merge(doc, 1, doc.GetNumberOfPages());
doc.Close();
});
ByteContent = ms.ToArray();
document.Close();
Merging is a really straightforward process:
var SourceDocument1 = new PdfDocument(new PdfReader(SRC));
var SourceDocument2 = new PdfDocument(new PdfReader(SRC1));
byte[] result;
using (var memoryStream = new MemoryStream())
{
var pdfWriter = new PdfWriter(memoryStream);
var pdfDocument = new PdfDocument(pdfWriter);
PdfMerger merge = new PdfMerger(pdfDocument);
merge.Merge(SourceDocument1, 1, SourceDocument1.GetNumberOfPages())
.Merge(SourceDocument2, 1, SourceDocument2.GetNumberOfPages());
merge.Close();
result = memoryStream.ToArray();
}
File.WriteAllBytes(#"C:\temp\file.pdf", result);
this will merge SRC with SRC1.
There are a lot of examples on Github, such as this one (there is also a whole folder with merge examples).
I am writing the destination document in the end, just to make sure it's being created correctly, but you can do whatever you want to with the MemoryStream, of course.

How to make file flatten while merging two PDF using IronPdf?

I have two PDF files and I want to merge two PDF files in single PDF files using IronPDF (reference from https://ironpdf.com/). Here is the code I am using
var PDFs = new List<PdfDocument>();
foreach (var file in files)
{
PDFs.Add(PdfDocument.FromFile(file));
}
PdfDocument PDF = PdfDocument.Merge(PDFs);
newFileName = Path.Combine(TEMP_PDF_FILESTORE_LOCATION, newFileName);
PDF.SaveAs(newFileName);
While merging two PDF files here is the error it showing "Could not safely read page objects from AnotherPdfFile". One of PDF can contain image in that. Some image PDF it will take some throw error.
How we can remove this error?
I got the same error (Could not safely read page objects from AnotherPdfFile) when I tried to merge PDF documents that were constructed using streams that came from another service.
In order to solve this, I had to first copy each stream into a MemoryStream and then passing in the memory stream into the PdfDocument constructor. Using memory streams, IronPdf was able to merge these.

C# iTextSharp: The process cannot access the file because it is being used by another process

I'm generating a pdf file from a template with iTextSharp, filling each field in this code portion:
PdfReader pdfReader = new PdfReader(templatePath);
try
{
using (FileStream newFileStream = new FileStream(newFilePath, FileMode.Create))
{
using (PdfStamper stamper = new PdfStamper(pdfReader, newFileStream))
{
// fill each field
AcroFields pdfFormFields = stamper.AcroFields;
foreach (KeyValuePair<string, string> entry in content)
{
if (!String.IsNullOrEmpty(entry.Value))
pdfFormFields.SetField(entry.Key, entry.Value);
}
//The below will make sure the fields are not editable in
//the output PDF.
stamper.FormFlattening = true;
stamper.Close();
}
}
}
finally
{
pdfReader.Close();
}
Everything goes fine, file looks ok, but when i try to reopen the file to merge it with some other files I've generated in a unique document i get this error:
2015-11-23 09:46:54,651||ERROR|UrbeWeb|System.IO.IOException: The process cannot access the file 'D:\Sviluppo\communitygov\MaxiAnagrafeImmobiliare\MaxiAnagrafeImmobiliare\cache\IMU\E124\admin\Stampe\Provvedimento_00223850306_2015_11_23_094654.pdf' because it is being used by another process.
Error occurs at this point
foreach (Documento item in docs)
{
string fileName = item.FilePath;
pdfReader = new PdfReader(fileName); // IOException
// some other operations ...
}
Edit: Using Process monitor as suggested I can see there is no close CloseFile operation as I would expect. Can this be the source of the issue?
I've been stuck on this for hours any help is really really appreciated.
Had the same issue with me. This helped a lot.
"You're problem is that you are writing to a file while you are also reading from it. Unlike some file types (JPG, PNG, etc) that "load" all of the data into memory, iTextSharp reads the data as a stream. You either need to use two files and swap them at the end or you can force iTextSharp to "load" the first file by binding your PdfReader to a byte array of the file."
PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath));
Ref: Cris Haas answer to Cannot access the file because it is being used by another process
I had a similar problem with opening pdf files (for read only) with iTextSharp PdfReader. The first file gave no problem, the second one gave that exception (can not access the file, etc.).
After hours and googling and searching for complicate solutions and twisting my brain, only the simple following code resolved it fully:
iTextSharp_pdf.PdfReader pdfReader = null;
pdfReader = new iTextSharp_pdf.PdfReader(fileName);

Question about setting up FIle Writer in C#

Im using DirectShowLib in C#. I want to use File Writer in C# to set a file output. I want to use File Writer because Graph.SetOutputFileName() wont connect to my encoder, but File Writer will. How can i set the File that File Writer saves to in C#?
I tried pulling up its property pages like in the DxPropPages example but one won't come up for File Writer.
Pulled from here
IBaseFilter ibf = new FileWriter() as IBaseFilter;
Update:
"I know how to add file writer to my
graph in code i just dont know how to
set the file path"
try the following:
FileWriter fileWriter = new FileWriter();
IFileSinkFilter fileSinkFilter = (IFileSinkFilter)fileWriter;
fileSinkFilter.SetFileName(fileOutput, null);
Here a useful link that shows a full running example. the example is demonstrating the use of DES but you should get the general idea from it.

Categories

Resources