iTextSharp "The document has no pages." - c#

I'm using iTextSharp to update A PDF's file properties:
FileStream fs = File.Open(#"C:\Developer\C#Projects\BylawSearch\0001.pdf", FileMode.Open);
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
document.AddSubject("Blah");
document.AddTitle("Blah blah");
document.AddKeywords("Blah blah blah");
document.Close();
I'm getting a "The document has no pages." error from iTextSharp. Any help appreciated.

You haven't added any information to put on a page ... !!
document.Add(new Paragraph("Hello World!"));
... for example.
Your title etc are part of the document properties (rather than something that's "printed" to the pdf).
Check out this introductory example, that seems to cover what you're after.

In my case, I had added a paragraph, but specified a font that was null.
document.Add(new Paragraph("Hello World!", nullFont));
Either make sure the font is valid, or else don't use the Paragraph constructor with the Font argument.
(This does not apply to the poster's scenario, but may be helpful to someone else.)

I had the same issue with Xamarin, .NET. For me the error message was misleading, because it happened when i tried to create fonts from local files.
Project settings > Android Options > Additional supported encodings.
Set this to West and it solved my problem.

Related

Generating PDF in windows forms using XML reader

My windows form contains a textbox in which we need to enter html tags,One button to generate PDF.
And we need to load the textbox content into XML Reader and process each element of XML recursively then we need to generate a PDF file.
The PDF file must contain the data i.e;
for example if I entered tag in the text box in the pdf file it must display a table.
I am very new to Windows forms and XML also can any one help me to complete this task
You would need to use a library to create PDF files. iTextSharp is a common library which can help. Take a look at this library and samples, you would be able to create PDF files easily from your application
https://sourceforge.net/projects/itextsharp/
iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF):
iTextSharp is the .NET port.
Got Answer with this simple code
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw =
new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(htmlText));
document.Close();
but my problem is the path I want to select the path dynamically.Can any one help me how to set the path dynamically in the above code.
PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\MySamplePDF.pdf", FileMode.Create));
Changed this code by using a savefile dialog box
SaveFileDialog svg = new SaveFileDialog();
svg.ShowDialog();
PdfWriter.GetInstance(document, new FileStream(svg.FileName + ".pdf", FileMode.Create));

Creating and editing text in Word document in C#

I have used itextsharp for PDF documents and now I need to create and add a text to a Word document(I'm using OpenXml SDK) so I would like to know what classes and objects are used here to add a paragraph or to set the alingment and indentation or to set the basefont and size of font. For example, this is my code for creating PDF using iTextSharp and now I want to translate it to create Word:
Document document = new Document(iTextSharp.text.PageSize.A4, 40, 40, 50, 50);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFile.FileName, FileMode.Create));
document.Open();
document.NewPage();
Paragraph title = new Paragraph("aaa",titleFont);
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
document.Add(Chunk.NEWLINE);
Paragraph p1 = new Paragraph("",Font11);
p1.IndentationLeft = 20f;
document.Add(p1);
The best way to discover the things you ask about is to download the Open XML SDK Productivity Tool from Microsoft's site. Create a small, sample document in Word (as a user), save it, close it, then open it in the Productivity Tool. That can show you both the underlying XML as well as standard code for generating the document. That way you can see what objects are used and how they're put together.
This is have I done it with DocX.dll:
var document = DocX.Create(wordFile.FileName);
Novacode.Paragraph title = document.InsertParagraph("AAA", false, titleFormat);
title.Alignment = Alignment.center;
document.InsertParagraph(Environment.NewLine);
document.Save();
Process.Start("WINWORD.exe", wordFile.FileName);

MVCRazorToPdf (iTextSharp) using custom font

I am trying to add a custom font to my pdf output using the nuget package MVCRazorToPdf but I am having trouble with how to do this as the documentation for iTextSharp isn't great and all seems to be outdated.
The current code I have for creating the pdf is:
return new PdfActionResult(
"test.cshtml",
new TestModel(),
(writer, document) =>
{
FontFactory.Register(HostingEnvironment.MapPath("~/content/fonts/vegur-regular-webfont.ttf"), "VegurRegular");
});
Where writer is a PdfWriter and document is a Document
All the examples of using the FontFactory show that you need to use the XmlWorker but I don't have access to that, so I was wondering if there was any way to change the documents font using the writer or document?
I've seen that there is the document.HtmlStyleClass property but can't find anything about how to use this anywhere.
Any help with this would be greatly appreciated
MVCRazorToPdf is a very, very simple wrapper around iTextSharp's XMLWorker and uses the even simpler XMLWorkerHelper with all defaults to do its work. If you look at the source you'll see this:
document.Open();
using (var reader = new StringReader(RenderRazorView(context, viewName)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);
document.Close();
output = workStream.ToArray();
}
If you're dead-set on using the NuGet version then you're stuck with this implementation and you're not going to be able to register a custom font.
However, there's an open issue regarding this that includes a fix so if you're willing to compile from source you can apply that change and you should be all set.
If you want to go one step further I'd recommend reading this great post that shows how simple parsing HTML with iTextSharp is as well Bruno's post here that shows how to register fonts.
EDIT
As per the post in the includes a fix link (just in case the link breaks in future), change the above using statement to:
using (var reader = new MemoryStream(Encoding.UTF8.GetBytes(RenderRazorView(context, viewName))))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader, null, FontFactory.FontImp as IFontProvider);
document.Close();
output = workStream.ToArray();
}
And then the font factory as registered in the question above will work when using style="font-family:VegurRegular;"

Preview PDF before save it

I want to preview a PDF file.
I used iTextSharp in C# to generate the PDF file.
How can I make a function to preview PDF file before print it.
I didn't find anything on the preview with iTextSharp
I did find an answer of my question and I want to shared it with all.
So, I have make a personnal viewer with Windows.Data.Pdf library.
I would just open the By saving it the opening it then having a check to see if it is open and if it isn't open anymore deleting it.
Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 20, 10);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("submitted.pdf", FileMode.Create));
doc.Open();
// do your generating code here
doc.Close();
System.Diagnostics.Process.Start("filepath\\submitted.pdf");
System.IO.File.Delete("filepath\\submitted.pdf");

iTextSharp for PDF - how add file attachments?

I am using iTextSharp to create a PDF document in C#. I would like to attach another file to the PDF. I'm having just loads of trouble trying to do so. The examples here show some annotations, which apparently attachments are.
This is what I've tried:
writer.AddAnnotation(its.pdf.PdfAnnotation.CreateFileAttachment(writer, new iTextSharp.text.Rectangle(100,100,100,100), "File Attachment", its.pdf.PdfFileSpecification.FileExtern(writer, "C:\\test.xml")));
Well, what happens is it does add an annotation on the PDF (appears as a little comment voice balloon), which i don't want. test.xml is shown in the attachments pane in Adobe Reader, but it can't be read or saved, and its file size is unknown so it's likely that it's never being properly attached.
Any suggestions?
Well, I got some code working to attach it:
its.Document PDFD = new its.Document(its.PageSize.LETTER);
its.pdf.PdfWriter writer;
writer = its.pdf.PdfWriter.GetInstance(PDFD, new FileStream(targetpath, FileMode.Create));
its.pdf.PdfFileSpecification pfs = its.pdf.PdfFileSpecification.FileEmbedded(writer, "C:\\test.xml", "New.xml", null);
writer.AddFileAttachment(pfs);
where "its"="iTextSharp.text"
Now to read the attachment!

Categories