I have two PDF files: Pdf A and Pdf B. Pdf A already exists on the computer's C: drive and Pdf B gets generated through the program which also lands in the C: drive.
What I want to do is combine the two so that the Pdf A's pages show first and then Pdf B's pages show after that.
Here is my code that tries to combine the two given a list of PDFs (Pdf A is the first element and Pdf B is the second element in the files list, and the destinationfile is Pdf A):
public static void MergePdfFiles(string destinationfile, List<string> files)
{
Document document = null;
try
{
List<PdfReader> readers = new List<PdfReader>();
List<int> pages = new List<int>();
foreach (string file in files)
{
readers.Add(new PdfReader(file));
}
document = new Document(readers[0].GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));
document.Open();
foreach (PdfReader reader in readers)
{
pages.Add(reader.NumberOfPages);
WritePage(reader, document, writer);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//being used by another process
document.Close();
}
}
The issue appears when the document object tries to close. It says it is being used another process.
What 'other' process is using it?
try to change this line:
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));
to this line :
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create,FileAccess.Write,FileShare.ReadWrite));
Related
I can create multiple pdf documents using iText 7. However, after creation I want to send an email with the newly created pdfs as attachments. This results in sharing violation error. See my steps below.
First I have a static class to initialize pdfs called PDFLibrary:
public static PdfWriter CreateWriter(string Filepath)
{
//set writer properties
WriterProperties writerProperties = new WriterProperties();
writerProperties.SetStandardEncryption(Encoding.ASCII.GetBytes(""), Encoding.ASCII.GetBytes("password"), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128);
PdfWriter writer = new PdfWriter(Filepath, writerProperties);
//set compression level
writer.SetCompressionLevel(9); //0 = best speed, 9 = best compression, -1 is default
return writer;
}
public static PdfDocument CreatePDFDocument(PdfWriter Writer)
{
return new PdfDocument(Writer);
}
public static Document CreateDocument(PdfDocument PDFDoc)
{
Document document = new Document(PDFDoc);
document.SetMargins(25,25,25,25);
return document;
}
Then I reference the above class and methods:
PdfWriter writer;
PdfDocument pdfDocument;
Document doc;
private void CreatePDFs(string PDFPath)
{
writer = PDFLibrary.CreateWriter(PDFPath);
pdfDocument = PDFLibrary.CreatePDFDocument(writer);
doc = PDFLibrary.CreateDocument(pdfDocument);
}
Finally (after adding tables and cells to create the desired pdfs), I close the pdf objects:
private void CloseDocumentStreams()
{
doc.Close();
writer.SetCloseStream(true);
writer.Close();
}
Now attempting the following operation in a send email method results in an "IOException: Sharing violation on path":
Attachment attachment = new Attachment(pathToPDF[i]);
Is there a way to fully release iText's handle over the documents? The example documentation only shows document.Close() where document is type Document.
I use the itextsharp library to remove unwanted bookmarks from PDF files.
I developed the following code:
private static void RemovePDFbookmarks(string filein, string fileout)
{
PdfReader pdfReader = new PdfReader(filein);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileStream(fileout, FileMode.Create));
document.Open();
copy.AddDocument(pdfReader);
document.Close();
pdfReader.Close();
copy.Close();
}
This method creates a copy of the original file. During the following process, I need to delete the original file and rename the new file back to the original file's name.
How can I remove the bookmarks in the original PDF without the copy-delete-rename detour?
I want to create a PDF document containing some text that I have in the form of a string. This is what I have so far:
iTextSharp.text.Document d = new iTextSharp.text.Document();
string dosya = (#"C:\Deneme.pdf");
PdfWriter.GetInstance(d, new System.IO.FileStream(dosya, System.IO.FileMode.Create));
d.AddSubject(text);
Your question is unclear because you don't mention if you want to create a PDF from scratch (which may be what you want to do based on your code sample) or if you want to add text to an existing PDF (which is what the subject of your question suggests).
In both cases, you should take a look at the official documentation.
If you want to create a PDF from scratch, take a look at the Hello World example:
public void CreatePdf(Stream stream) {
// step 1
using (Document document = new Document()) {
// step 2
PdfWriter.GetInstance(document, stream);
// step 3
document.Open();
// step 4
document.Add(new Paragraph("Hello World!"));
}
}
The value of stream can be any output stream (one that writes to memory, one that writes to a file,...).
If you want to add a string to an existing PDF, take a look at a PdfStamper example.
public static byte[] Stamp(byte[] resource) {
PdfReader reader = new PdfReader(resource);
using (var ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
PdfContentByte canvas = stamper.GetOverContent(1);
ColumnText.ShowTextAligned(
canvas,
Element.ALIGN_LEFT,
new Phrase("Hello people!"),
36, 540, 0
);
}
return ms.ToArray();
}
}
These examples were taken from a book I once wrote. You will find the examples through this link: http://developers.itextpdf.com/examples/itext-action-second-edition
This answer assumes that you are using iText 5 (an assumption that is based on your code snippet). The most recent version is iText 7. That requires code that is totally different.
How can I generate a pdf in winRT apps? I'm using iTextSharp to generate pdfs in windows store apps, but winRT does not have filestream, filemode or filedirectory. help
Here is my code:
iTextSharp.text.pdf.PdfWriter writer =
iTextSharp.text.pdf.PdfWriter.GetInstance(
doc, new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() +
"\\ScienceReport.pdf", System.IO.FileMode.Create
)
);
I can generate a PDF file in winrt
string path = #"ExportPDF.pdf";
var storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create empty PDF file.
var file = await storageFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
if (file != null)
{
await FileIO.WriteTextAsync(file, string.Empty);
}
// Open to PDF file for read/write.
StorageFile sampleFile = await storageFolder.GetFileAsync(path);
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
// Create an instance of the document class which represents the PDF document itself.
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
// Create an instance to the PDF file by creating an instance of the PDF
// Writer class using the document and the filestrem in the constructor.
PdfWriter writer = PdfWriter.GetInstance(document, stream.AsStream());
// Add meta information to the document
document.AddAuthor("Jigs");
document.AddCreator("Sample application");
document.AddKeywords("PDF App");
document.AddSubject("Document subject - Describing the steps creating a PDF document");
document.AddTitle("The document title - PDF creation");
// Open the document to enable you to write to the document
document.Open();
// Add a simple and wellknown phrase to the document in a flow layout manner
document.Add(new Paragraph("Hello!"));
// Close the document
document.Close();
// Close the writer instance
writer.Close();
I'm trying to convert HTML to PDF with iTextSharp.
Here's my code:
Document doc = new Document(PageSize.A4);
StringReader reader = new StringReader(responseHtml);
FileStream pdfStream = new FileStream("C:\\temp\\foo.pdf", FileMode.OpenOrCreate);
PdfWriter writer = PdfWriter.GetInstance(doc, pdfStream);
doc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, reader);
doc.Close();
The issue is that the PDF file stops after 2 pages.
The rest of the content just doesn't make it to the PDF file.
When I change the PageSize to A1, I get the whole content, 'cause it fits on two A1 pages.
How do I get it to create more than two pages?