I am having trouble writing multiple pages to an xps document. I have a loop that goes through my opened windows and saves the last window. this presents to a pdf fine, however it is just the last window in wpf.
MemoryStream lMemoryStream = new MemoryStream();
Package package = Package.Open(lMemoryStream, FileMode.Create);
XpsDocument doc = new XpsDocument(package);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
writer.Write(Report.reportWindow);
doc.Close();
package.Close();
var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream);
PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, filename, 0);
I have tried changing the FileMode to Append. However, this comes up with an error "Append and Truncate not supported".
Related
I have a PDF document (using iText 7/C# 4.01) that I am creating in a MemoryStream and at the end, I want to write it out to a file. Part of the reason I am creating it in a memory stream is that I want to stamp a header table and footers on it at the end and was hoping to avoid writing it to a file then reading the file back in, stamping, then writing out a new file (as the examples I keep finding on iText website seem to do). However, I seem to be having some sort of chicken/egg scenario in the below code. It seems that you have to Close() the document in order for iText to fully form it. However, if I Close() it, then I get an ObjectDisposedException when trying to write it (simplified example below). I have to be missing something simple here, right? Thanks
MemoryStream baos = new MemoryStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdfDocument = new PdfDocument(writer.SetSmartMode(true));
//writer.SetCloseStream(true);
//pdfDocument.SetCloseWriter(true);
//pdfDocument.SetCloseReader(true);
//pdfDocument.SetFlushUnusedObjects(true);
Document d = new Document(pdfDocument, iText.Kernel.Geom.PageSize.LETTER);
d.Add(new Paragraph("Hello world!"));
//d.Close();
FileStream file = new FileStream("C:\test.pdf",
FileMode.Create, FileAccess.Write);
baos. WriteTo(file);
file.Close();
//baos.Close();
//d.Close();
Try this
I dont have IDE for test, but i think this work
MemoryStream baos = new MemoryStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdfDocument = new PdfDocument(writer.SetSmartMode(true));
Document d = new Document(pdfDocument, iText.Kernel.Geom.PageSize.LETTER);
d.Add(new Paragraph("Hello world!"));
d.Close();
byte[] byte1 = baos.ToArray();
File(byte1, "application/pdf", "C:\\iTextTester\\test.pdf");
I am trying to write to a pdf and send it in an email.I am able to implement this on my local machine. The problem is when I deploy to azure I am not sure where to store the pdf . I have seen one question regarding this
and tried this solution from stackoverflow -
Does iText (any version) work on Windows Azure websites?.
var path = Server.MapPath("test.pdf");
FileInfo dest = new FileInfo(path);
var writer = new PdfWriter(dest);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("hello world"));
document.Close();
I get an error
Could not find a part of the path
'D:\home\site\wwwroot\Email\test.pdf'.
Try to create the Pdf in memory and stream the content to the asp.net output stream.
Document document = new Document(PageSize.A4);
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.NewPage();
...
...
document.Close();
Response.Clear();
Response.ContentType = "application/pdf";
byte[] pdfBytes = ms.ToArray();
Response.AppendHeader("Content-Length", pdfBytes.Length.ToString());
Response.OutputStream.Write(pdfBytes, 0, (int)pdfBytes.Length);
I suppose your issue is related with the file path.
If I use the path like Server.MapPath("Azure_Example1.pdf"), I also get the same error as you.
I suggest you could try to use the relative path like Server.MapPath("~/Azure_Example1.pdf"). The '~/' points to the project root directory.
You could also set a break point to check the value of path by using remote debugging.
I have created a simple demo, it works fine on my side. You could refer to.
Install the iTextSharp 5.5.13 nuget package in Manage Nuget Packages.
Use the following code:
var path = Server.MapPath("~/Azure_Example1.pdf");
FileInfo dest = new FileInfo(path);
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
doc.Add(new Paragraph("Hello World")); //change content in pdf
doc.Close();
Finally, you could see the pdf file has been stored in root project directory.
In vb.net I need to print the contents showing in a browser control to printer.
I have used Gecko web-browser control in winform application and there is no direct way to print the page's contents.
Either way to print direct using InnerHtml or converting that html to pdf and then printing the pdf document.
currently I am using a third party library `ItextSharpe' but it gives errors.
public byte[] GetPDF(string pHTML) {
byte[] bPDF = null;
MemoryStream ms = new MemoryStream();
TextReader txtReader = new StringReader(pHTML);
// 1: create object of a itextsharp document class
Document doc = new Document(PageSize.A4, 25, 25, 25, 25);
// 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);
// 3: we create a worker parse the document
HTMLWorker htmlWorker = new HTMLWorker(doc);
// 4: we open document and start the worker on the document
doc.Open();
htmlWorker.StartDocument();
// 5: parse the html into the document
htmlWorker.Parse(txtReader);
// 6: close the document and the worker
htmlWorker.EndDocument();
htmlWorker.Close();
doc.Close();
bPDF = ms.ToArray();
return bPDF;
}
Byte[] bytes;
bytes = GetPDF(browse.Document.Body.InnerHtml);
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);
but throws errors while parsing.
Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph'.
I have seen different examples over web but this is totally different, the examples or duplicate answer is about to export panels or grids but this is dynamic HTML and i need to convert it to PDF or print directly the client area.
I have an XFA PDF file (which I did not author). It's a third-party form which I'm trying to fill out. I filled out the form manually, then I used iTextSharp save the full XML DomDocument from it. Now I'm trying to apply that same XML file programmatically. However, the resulting PDF doesn't have any of the fields filled in. This is the code I'm using to apply the XML file:
PdfReader pdfReader = new PdfReader(inputPdf);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms, '\0', true))
{
XfaForm xfaForm = new XfaForm(pdfReader);
XmlDocument doc = new XmlDocument();
doc.Load(inputXml);
xfaForm.DomDocument = doc;
xfaForm.Changed = true;
XfaForm.SetXfa(xfaForm, stamper.Reader, stamper.Writer);
}
var bytes = ms.ToArray();
System.IO.File.WriteAllBytes(outputPdf, bytes);
}
inputPdf is the path to the original empty PDF file.
inputXml is the path to the XML file extracted from the filled out PDF file. This is the entire XML file, and not just the datasets section.
What's interesting is that if I create the PdfStamper object like this instead:
new PdfStamper(pdfReader, ms);
then I see the data in the fields, but of course then I have the associated issues with not appending.
Any suggestions on what I might be doing wrong? I just can't seem to get any of the changes to the DomDocument to save.
I've recently used iTextSharp to create a PDF by importing the 20 pages from an existing PDF and then adding a dynamically generated link to the bottom of the last page. It works fine... kind of. Viewing the generated PDF in Acrobat Reader on a windows PC displays everything as expected although when closing the document it always asks "Do you want to save changes?". Viewing the generated PDF on a Surface Pro with PDF Reader displays the document without the first and last pages. Apparently on a mobile device using Polaris Office the first and last pages are also missing.
I'm wondering if when the new PDF is generated it's not getting closed off quite properly and that's why it asks "Do you want to save changes?" when closing it. And maybe that's also why it doesn't display correctly in some PDF reader apps.
Here's the code:
using (var reader = new PdfReader(HostingEnvironment.MapPath("~/app/pdf/OriginalDoc.pdf")))
{
using (
var fileStream =
new FileStream(
HostingEnvironment.MapPath("~/documents/attachments/DocWithLink_" + id + ".pdf"),
FileMode.Create, FileAccess.Write))
{
var document = new Document(reader.GetPageSizeWithRotation(1));
var writer = PdfWriter.GetInstance(document, fileStream);
using (PdfStamper stamper = new PdfStamper(reader, fileStream))
{
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252,
BaseFont.NOT_EMBEDDED);
Font linkFont = FontFactory.GetFont("Arial", 12, Font.UNDERLINE, BaseColor.BLUE);
document.Open();
for (var i = 1; i <= reader.NumberOfPages; i++)
{
document.NewPage();
var importedPage = writer.GetImportedPage(reader, i);
// Copy page of original document to new document.
var contentByte = writer.DirectContent;
contentByte.AddTemplate(importedPage, 0, 0);
if (i == reader.NumberOfPages) // It's the last page so add link.
{
PdfContentByte cb = stamper.GetOverContent(i);
//Create a ColumnText object
var ct = new ColumnText(cb);
//Set the rectangle to write to
ct.SetSimpleColumn(100, 30, 500, 90, 0, PdfContentByte.ALIGN_LEFT);
//Add some text and make it blue so that it looks like a hyperlink
var c = new Chunk("Click here!", linkFont);
var congrats = new Paragraph("Congratulations on reading the eBook! ");
congrats.Alignment = PdfContentByte.ALIGN_LEFT;
c.SetAnchor("http://www.domain.com/pdf/response/" + encryptedId);
//Add the chunk to the ColumnText
congrats.Add(c);
ct.AddElement(congrats);
//Tell the system to process the above commands
ct.Go();
}
}
}
}
}
I've looked at these posts with similar issues but none seem to quite provide the answer I need:
iTextSharp-generated PDFs cause save dialog when closing
Using iTextSharp to write data to PDF works great, but Acrobat Reader asks 'Do you want to save changes' when closing file
(Or they refer to memory streams instead of writing to disk etc)
My question is, how do I modify the above so that when closing the generated PDF in Acrobat Reader there's no "Do you want to save changes?" prompt. The answer to that may solve the problems with missing pages on Surface Pro etc but if you know anything else about what might be causing that I'd like to hear about it.
Any suggestions would be very welcome! Thanks!
At first glance (and without much coffee yet) it appears that you're using a PdfReader in three different contexts, as a source to a PdfStamper, as a source for Document and as for a source for importing. So you are essentially importing a document into itself that you're also writing to.
To give you a quick overview, the following code will essentially clone the contents of source.pdf into dest.pdf:
using (var reader = new PdfReader("source.pdf")){
using (var fileStream = new FileStream("dest.pdf", FileMode.Create, FileAccess.Write)){
using (PdfStamper stamper = new PdfStamper(reader, fileStream)){
}
}
}
Since that does all of the cloning for you you don't need to import pages or anything.
Then, if the only thing that you want to do is add some text to the last page, you can just use the above and ask the PdfStamper for a PdfContentByte using GetOverContent() and telling it what page number you're interested. Then you can just use the rest of your ColumnText logic.
using (var reader = new PdfReader("Source.Pdf")) {
using (var fileStream = new FileStream("Dest.Pdf"), FileMode.Create, FileAccess.Write) {
using (PdfStamper stamper = new PdfStamper(reader, fileStream)) {
//Get a PdfContentByte object
var cb = stamper.GetOverContent(reader.NumberOfPages);
//Create a ColumnText object
var ct = new ColumnText(cb);
//Set the rectangle to write to
ct.SetSimpleColumn(100, 30, 500, 90, 0, PdfContentByte.ALIGN_LEFT);
//Add some text and make it blue so that it looks like a hyperlink
var c = new Chunk("Click here!", linkFont);
var congrats = new Paragraph("Congratulations on reading the eBook! ");
congrats.Alignment = PdfContentByte.ALIGN_LEFT;
c.SetAnchor("http://www.domain.com/pdf/response/" + encryptedId);
//Add the chunk to the ColumnText
congrats.Add(c);
ct.AddElement(congrats);
//Tell the system to process the above commands
ct.Go();
}
}
}