Generate a PDF document from a webpage with style intact - css

I am using the iTextSharp library to convert a web page to a PDF document.
Although the document is successfully generated, the CSS applied on the webpage is not being applied in the PDF.
I take the HTML Markup and save it as a text file.
After that, I access that file and put the content into a string.
That markup gets converted in webpage and then into PDF.
But I am not able to apply any css to it.
Example Code:
using (MemoryStream stream = new MemoryStream())
{
Gridhtml = Gridhtml.Replace("\n", "").Replace("\r", "");
System.IO.File.WriteAllText(System.Web.HttpContext.Current.Server.MapPath("~/Content/HtmlTable/HtmlTableMarkup.txt"),Gridhtml);
StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/Content/HtmlTable/HtmlTableMarkup.txt"));
Document pdfdoc = new Document(PageSize.A4,10f,10f,100f,0f);
PdfWriter pdfw = PdfWriter.GetInstance(pdfdoc,stream);
pdfdoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(pdfw,pdfdoc,sr);
pdfdoc.Close();
return File(stream.ToArray(), "applicationpdf", "Grid.pdf");
}
How can I obtain the PDF with the same styling as the webpage?

Related

C# iTextSharp PdfCopy to MemoryStream copies entire document and single page

I am trying to make a one page PDF from a 3 page PDF document using memory stream. But when the code below executes, all 3 pages get added and not just the first page.
What am I missing here? Please help.
Note: I am using iTextSharp v5.5.13
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
MemoryStream ms = new MemoryStream();
byte[] fileToBeEncrypted = null;
string sSourcePDF = "C:\\my3pageFile.pdf;
PdfReader pdfReader = new PdfReader(sSourcePDF);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, ms) {CloseStream = false};
document.Open();
copy.AddPage(copy.GetImportedPage(pdfReader, iPage));
document.Close();
fileToBeEncrypted = ms.ToArray(); //returns the ENTIRE DOCUMENT AND NOT JUST PAGE 1
Can anyone help?
Thanks
Tom
The above code pdfCopy.GetImportedPages does works and I found an error further down in my own code.

How to write text on different page based on text of exiting pdf using itextsharp

How to write Text on different pages on exiting pdf which have more then 1 page.
For example 'Hitesh Second Page' I want to write this word on second page
'Hitesh Third Page' I want to write this word on Third page
Below code work only for pdf which have one page.
string fileName = "test.pdf";
string oldFile = System.Web.Hosting.HostingEnvironment.MapPath("~/AuthDoc/CoverPage.pdf");
string newFile = System.Web.Hosting.HostingEnvironment.MapPath(fileName);
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
string text = "";
cb.BeginText();
text = "Hitesh Third Page";
cb.ShowTextAligned(3, text,500,500, 0);
cb.EndText();
cb.BeginText();
text = "Hitesh Second Page";
cb.ShowTextAligned(2, text,500,500, 0);
cb.EndText();
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate( page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();
byte[] bytes = System.IO.File.ReadAllBytes(newFile);
return bytes;
Thanks,
Hitesh
When using a Document / PdfWriter pair to create a document, you create the pages in their final order, i.e. you first create the first page, then the second, then the third, ...
In your code you appear to try to start by creating the third page and then continue by creating the second one. You'll have to sort the code accordingly.
As soon as you have sorted your code, you can use the Document method NewPage to switch to the next page:
document.NewPage();
Beware, though, iText ignores the NewPage call if there is no content whatsoever on the page in question. To override this, you can make iText believe it is not empty using the PdfWriter property PageEmpty before calling NewPage:
writer.PageEmpty = false;
document.NewPage();
That been said, though...
How to write Text on different pages on exiting pdf
For such a task you should not use a Document / PdfWriter pair to start with, use a PdfReader / PdfStamper pair! In a PdfStamper you can quite freely jump between pages...

How to load image using URL from the WEF-INF\image folder to write in a PDF document

How to get image URL and used to write in a PDF document.
ClassPathResource classPathResource = new ClassPathResource("Image.png");
i have added the image logo like this in my pdf file
String imgPath = "/img/Kavi025.jpg";
String absoluteImgPath = getServletContext().getRealPath(imgPath);
System.out.println(absoluteImgPath);
Document document= new Document();
PdfWriter writer= PdfWriter.getInstance(document, new FileOutputStream("d:\\Kavi.pdf"));
document.open();
Image img = Image.getInstance(absoluteImgPath);
img.setAbsolutePosition(100, 200); // x-axis and y-axis position
writer.getDirectContent().addImage(img);
document.close();
System.out.println("end of method");

itextsharp PdfStamper.AcroFields.SetField giving error

I have a PDF containing Chinese, Japanese language. In that PDF I have some input fields. I want to fill this PDF dynamically in C#.net
I am using iTextSharp dll to read pad and successfully read the PDF fields but when I am going to set value with PdfStamper.AcroFields.SetField, it gives me this error
Font 'KozMinPro-Regular' with 'UniJIS-UCS2-H' is not recognized.
To read PDF and getting fields I am using the following code
string pdfTemplate = #"C:\Users\admin\Desktop\test.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
And I am getting all fields successfully.
To fill data in PDF I am using this code
string pdfTemplate = #"C:\Users\admin\Desktop\test.pdf";
string newFile = #"C:\Users\admin\Desktop\newdata_test.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// set form pdfFormFields
pdfFormFields.SetField("fill_17", "test");
I am facing error on pdfFormFields.SetField method as
Font 'KozMinPro-Regular' with 'UniJIS-UCS2-H' is not recognized.
Please advice what I have to change or how I can resolve this issue.
There are some files missing in your project. In order to use the font 'KozMinPro-Regular' with 'UniJIS-UCS2-H', you need to give iTextSharp access to the metrics files that contain information about that font. These metrics files can be downloaded separately from SourceForge. More specifically, you need the file iTextAsian-dll-2.1.zip that can be found in iTextAsian-all-2.1.zip
Note that this will only work with a recent version of iTextSharp (5.3.0.0 or higher). This iTextAsian DLL won't work with older versions of iTextSharp.

What's the easiest way to convert a BMP to a PDF in ASP.net

What's the easiest way to convert a BMP file to a single page PDF using ASP.net? I'm going to generate the 8.5" x 11" BMP in Flash (which means I can manipulate it to make it as easy as possible), then use a POST to upload it to an ASP page, which will convert it to a PDF and redirect the user to the PDF. I don't want to add any margins or anything else, it will be laid out properly in the BMP for full-bleed.
Would it be easier to convert it to PDF in Flash, then upload?
Thanks!
You can use iTextSharp to create a PDF and insert the image into the document. This can be done all in memory with a final PDF produced to client.
The following is an MVC method, stripped for display, but should see how to do this.
[HttpGet]
public FileStreamResult Export(int? ID)
{
MemoryStream stream = new MemoryStream();
Document pdf = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
PdfPTable tblImage = new PdfPTable(1);
tblImage.AddCell(Image.GetInstance(LogChart())); //The LogChart method returns image
pdf.Add(Image);
pdf.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}

Resources