Generate PDF from ASP.NET from raw HTML/CSS content? - c#

I'm sending emails that have invoices attached as PDFs. I'm already - elsewhere in the application - creating the invoices in an .aspx page. I'd like to use Server.Execute to return the output HTML and generate a PDF from that. Otherwise, I'd have to use a reporting tool to "draw" the invoice on a PDF. That blows for lots of reasons, not the least of which is that I'd have to update both the .aspx page and the report for every minor change. What to do...

There is no way to generate a PDF from an HTML string directly within .NET, but there are number of third party controls that work well.
I've had success with this one: http://www.html-to-pdf.net
and this: http://www.htmltopdfasp.net
The important questions to ask are:
Does it render correctly as compared to the 3 major browsers: IE, FF and Safari/Chrome?
Does it handle CSS fine?
Does the control have it's own rendering engine? If so, bounce it. You don't want to trust a home grown rendering engine - the browsers have a hard enough problem getting everything pixel perfect.
What dependencies does the third party control require? The fewer, the better.
There are a few others but they deal with ActiveX displays and such.

We use a product called ABCPDF for this and it works fantastic.
http://www.websupergoo.com/abcpdf-1.htm

This sounds like a job for Prince. It can take HTML and CSS and generate a PDF, which you can then present to your users. It supports CSS3 better than most web browsers (staff include HÃ¥kon Wium Lie, the inventor of CSS).
See the samples, especially the ones for Wikipedia pages, for the beautiful output it can generate. There's also an interesting Google Tech Talk with the authors.
Edit: There is a .NET wrapper available.

wkhtmltopdf is a free and cool exe to generate pdf from html. Its written in c++. But nReco htmltopdf is a wrapper dotnet library for this awesome tool. I implemented using this dotnet library and it was just so good it does everything by its own you just need to give html as a data source.
/// <summary>
/// Converts html into PDF using nReco dll and wkhtmltopdf.exe.
/// </summary>
private byte[] ConvertHtmlToPDF()
{
HtmlToPdfConverter nRecohtmltoPdfObj = new HtmlToPdfConverter();
nRecohtmltoPdfObj.Orientation = PageOrientation.Portrait;
nRecohtmltoPdfObj.PageFooterHtml = CreatePDFFooter();
nRecohtmltoPdfObj.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0";
return nRecohtmltoPdfObj.GeneratePdf(CreatePDFScript() + ShowHtml() + "</body></html>");
}
The above function is an excerpt from the below link post which explains it in detail.
HTML to PDF in ASP.Net

The initial question is about converting another aspx page containing an invoice to a PDF document. The invoice is probably using some session data and the user suggests to use Server.Execute() to obtain the invoice page HTML code and then to convert that code to PDF. Converting the invoice page URL directly is not possible because a new session would be created during conversion and the session data would be lost.
This is actually a good technique to preserve session data during conversion which is applied in Convert a HTML Page to PDF in Same Session ASP.NET Demo of the EvoPdf library. The complete C# code to get the HTML string rendered by the invoice page and to convert that string to PDF is:
// Execute the invoice page and get the HTML string rendered by this page
TextWriter outTextWriter = new StringWriter();
Server.Execute("Invoice.aspx", outTextWriter);
string htmlStringToConvert = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the page HTML string to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlStringToConvert, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Page_in_Same_Session.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();

As long as you can make sure to use proper XHTML, you could also use a product like Alt-Soft's Xml2PDF to convert XML (XHTML) into PDF by means of XSLT/XSL-FO.
It takes a bit of a learning curve to master, but it works very well once you've "got" it!
Marc

Since you are producing the answer, you can use a tool like Report.NET:
http://sourceforge.net/projects/report/
I disagree with the answers that say you cannot convert directly from output to PDF, however, as you can "re-call" the page and get the HTML as a stream and convert it. I am not sure what tool you would want to use to do this, however. In other words, it is possible, but I am not sure it is worth it. The PDF creation libs, like Report.NET, even though they force reusing some logic and no automagic converrsion, it is easier.
I have not tried this component, but I have heard good things about it from those who have. The model is more like HTML, but I am not sure you can simply send a rendered ASPX to it to create PDF:
http://www.websupergoo.com/abcpdf-8.htm

If you try to find some html to pdf software via GOOGLE you'll get a pile of this stuff.
There are about 10 leaders but most of them use IE dlls in background mode.
Just couple of them use their own parsing engine.
Please try PDF Duo .NET component in your ASP.NET project if you wish to create a PDF programaticaly.
It is light component for a cool generating of PDF invoces, reports e.g.

I'd go a different route. Assuming you are using SQL Server, use SSRS and generate the PDF that way.

A possible minimal solution to use Server.Execute() to obtain the HTML of the invoice page and convert that code to a PDF using winnovative html to pdf api for .net is:
TextWriter outTextWriter = new StringWriter();
Server.Execute("Invoice.aspx", outTextWriter);
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
byte[] pdfBytes = htmlToPdfConverter.ConvertHtml(outTextWriter.ToString(),
httpContext.Current.Request.Url.AbsoluteUri);

You can use PDFSharp or iTextSharp to convert html to pdf. PDFSharp is not free.

Related

ASP.NET converting HTML to PDF

I have tried multiple plugins and c# classes to try and convert the HTML and CSS on my asp.net project to a pdf and even though the code used looks fine, and the button click works for other functions, I just cannot seem to get any html to pdf function to work. Has anyone else encountered this, or know if there is something I have missed to resolve it?
This is the latest code I have tried for hiqpdf in C#:
protected void Print_Button_Click(object sender, EventArgs e)
{
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// set PDF page size, orientation and margins
htmlToPdfConverter.Document.PageSize = PdfPageSize.A4;
htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait;
htmlToPdfConverter.Document.Margins = new PdfMargins(0);
// convert HTML to PDF
htmlToPdfConverter.ConvertUrlToFile("http://localhost:51091/Printout","mcn.pdf");
}
It is not stated directly within theHiQpdf documentation of the method, but the method ConvertUrlToFile() stores the produced pdf file locally on the disc. On some example page (Convert URLs and HTML Code to PDF) the following comment can be found:
// ConvertUrlToFile() is called to convert the html document and save the resulted PDF into a file on disk
// Alternatively, ConvertUrlToMemory() can be called to save the resulted PDF in a buffer in memory
htmlToPdfConverter.ConvertUrlToFile(url, pdfFile);
Since your example shows a button-click eventhandler, the file is probably generated but not used to return in the http response. You have to write the data into the response. The methods ConvertToStream() or ConvertToMemory should come in handy to do so. Don't forget to use Response.Clear() or Response.ClearContent() and Response.ClearHeader() before that and Flush() and Close() afterwards.

Converting aspx page to image file

I have c# dynamic aspx page after new property add I create for record brochure
http://veneristurkey.com/admin/Brochure.aspx?Admin=PropertiesBrochureA4&id=36
but I want to this convert image file I am searching on internet but all with webbrowser and windows forms. I need on page load show not css type also image file. jpg, png or tiff how i can do this. i need to see sample code..
saving aspx page into an image 2
As I mentioned in my comment, your best bet is to opt for attempting to render HTML to an image.
Here is the link for a library that will allow your to render html to an image:
http://htmlrenderer.codeplex.com/
Here is code that does exactly what you're asking:
http://amoghnatu.wordpress.com/2013/05/13/converting-html-text-to-image-using-c/
Now all you have left is to get the html, since I'm assuming you don't want this to render to the browser prior to generating this image - you should look into grabbing the rendered html from the aspx page on the server prior to returning it, and then just return the image. To render a page:
https://stackoverflow.com/a/647866/1017882
Sorted.
If you do not mind using a commandline tool you can have a look at wkhtmltopdf. The package include a wkhtmltoimage component that can be used to convert HTML to image, using
wkhtmltoimage [URL] [Image Path]
Codaxy also wrote a wkhtmltopdf c# wrapper available through the NuGet package manager. I'm not sure if the wkhtmltoimage component was included, but it should be easy enough to figure out how they wrap the wkhtml components.
i fixed my problem with screenshot machine API they are my code..
public void resimyap()
{
var procad = WS.Satiliklars.Where(v => v.ForSaleID == int.Parse(Request.QueryString["id"])).FirstOrDefault();
var imageBytes = GetBytesFromUrl("http://api.screenshotmachine.com/?key=xxxxxx&size=F&url=http://xxxxxxx.com/a4.aspx?id=" + procad.ForSaleID);
string root = Server.MapPath("~/");
// clean up the path
if (!root.EndsWith(#"\"))
root += #"\";
// make a folder to store the images in
string fileDirectory = root + #"\images\a4en\";
// create the folder if it does not exist
if (!System.IO.Directory.Exists(fileDirectory))
System.IO.Directory.CreateDirectory(fileDirectory);
WriteBytesToFile( fileDirectory + + procad.ForSaleID + ".png", imageBytes);
Yes i also try wkhtmltopdf c# wrapper but in pdf or image converting time my computer fan goin crayz. also i must upload server exe file and my hosting firm didnt support them

Save Image to word of HTML reference

I export data from my database to word in HTML format from my web application, which works fine for me , i have inserted image into record,
the document displays the image also , all works fine for me except when i save that file and send to someone else .. ms word will not find link to that image
Is there anyway to save that image on the document so path issues will not raise
Here is my code : StrTitle contains all the HTML including Image links as well
string strBody = "<html>" +
"<body>" + strTitle +
"</body>" +
"</html>";
string fileName = "Policies.doc";
//object missing = System.Reflection.Missing.Value;
// You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Write(strBody);
You can create your html img tag with the image data encoded with base64. This way the image data is contained in the html document it self.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
You images are probably only available via filesystem (i.e. their src starts with file).
There are a few ways
Make the image available via the internet: make sure their src starts with http and that they are hosted on a web server visible to the downloader (for example, the same server from which they are dowonloading the image)
Use a library, for example see NuGet
You can inline the images as #DevZer0 suggests.
Based on experience
Is the simplest to implement but has some annoyances (the server needs to be available to the user)
Is probably the best way if you do a lot of Word or Office files manipulation.
Can be done and it would solve the problem, although you wouldn't have a full library to support further use cases.
Use a word document creation library if you really want to have flexibility in creating doc or docx type files. Like all other popular document formats, the structure needs to be accurate enough for the program that opens up the documents. Like you obviously cannot create a PDF file just by setting content type "application/PDF", if your content is not in a structure that PDF reader expects. Content type would just make the browser identify the extension (incorrectly in this case) and download it as a PDF, but its actually simple text. Same goes for MS word or any other format that requires a particular document structure to be parsed and displyed properly.
Since every picture, table is of type shape in Word/Excel/Powerpoint, you could simply add with your program an AlternativeText to your picture, which would actually save a URL of the download URL and when you open, it will retrieve its URL and replace it.
foreach (NetOffice.WordApi.InlineShape s in docWord.InlineShapes)
{
if (s.Type==NetOffice.WordApi.Enums.WdInlineShapeType.wdInlineShapePicture && s.AlternativeText.Contains("|"))
{
s.AlternativeText=<your website URL to download the picture>;
}
}
This would be the C# approach, but would require more time for the picture. If you write a small software for it, which replaces all pictures which contain a s.AlternativeText, you could replace a lot of pictures at same time.
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(s.AlternativeText, false, true);
It will look for the picture at that location.
You can do that for your whole document with the 1 loop I wrote you. Means, if it is a picture and contains some AlternativeText, then inside you loop you use the AddPicture function.
Edit: Anoter solution, would be to set a hyperlink to your picture, which would actually go to a FTP server where the picture is located and when you click on the picture, it will open it, means he can replace it by himself(bad, if you have 200 pictures in your document)
Edit according Clipboard:
string html = Clipboard.GetText(TextDataFormat.Html);
File.WriteAllText(temporaryFilePath, html);
NetOffice.WordApi.InlineShape i=appWord.ActiveDocument.InlineShapes.AddPicture(temporaryFilePath, false, true);
The Clipboard in Word is capable to transform a given HTML and when you paste it to transform that table or picture into Word. This works too for Excel, but doesn't for Powerpoint. You could do something like that for your pictures and drag and drop from your database.

How to get raw page source (not generated source) from c#

The goal is to get the raw source of the page, I mean do not run the scripts or let the browsers format the page at all. for example: suppose the source is <table><tr></table> after the response, I don't want get <table><tbody><tr></tr></tbody></table>, how to do this via c# code?
More info: for example, type "view-source:http://feeds.gawker.com/kotaku/full" in the browser's address bar will give u a xml file, but if you just call "http://feeds.gawker.com/kotaku/full" it will render a html page, what I want is the xml file. hope this is clear.
Here's one way, but it's not really clear what you actually want.
using(var wc = new WebClient())
{
var source = wc.DownloadString("http://google.com");
}
If you mean when rendering your own page. You can get access the the raw page content using a ResponseFilter, or by overriding page render. I would question your motives for doing this though.
Scripts run client-side, so it has no bearing on any c# code.
You can use a tool such as Fiddler to see what is actually being sent over the wire.
disclaimer: I think Fiddler is amazing

ASP.NET web page to PDF

I looking for the easiest way to export the currently viewed asp.net web page to a PDF document using iTextSharp - it can be either a screenshot of it or passing in the url to generate the document. Sample code would be greatly appreciated. Many thanks in advance!
On a past project, we used Supergoo ABCPDF
to do something like you need to and it worked quite well. You basicly feed it an url and it process the HTML page into a PDF.
On the downside, it's a licensed software with costs associated to it and we had some performance issues when exporting a lot of large PDF at the same time.
Hope this helps !
Adding to what Darin said in his comment.
You can try using wkhtmltopdf to generate PDF files. It takes URL as input. This is what I have used for my SO application so2pdf.
It is not that easy (or i think so), i had same problem and i had to write code to generate exact page in pdf. It depends of page and used styles etc. So i create drawing of each element.
For some project i used Winnovative HTML to PDF converter but it is not free.
Give a try with PDFSharp (to generate PDF files at runtime), and it's Open Source library :
http://pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=27&Itemid=1
Alternative solution : http://www.bratched.com/en/component/content/article/76-how-to-convert-xhtml-to-pdf-in-c.html
There is an example Convert the Current HTML Page to PDF on WInnovative website which does exactly this. The relevant C# code to convert the currently viewed asp.net web page to a PDF document is:
// Controls if the current HTML page will be rendered to PDF or as a normal page
bool convertToPdf = false;
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// The current ASP.NET page will be rendered to PDF when its Render method will be called by framework
convertToPdf = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (convertToPdf)
{
// Get the current page HTML string by rendering into a TextWriter object
TextWriter outTextWriter = new StringWriter();
HtmlTextWriter outHtmlTextWriter = new HtmlTextWriter(outTextWriter);
base.Render(outHtmlTextWriter);
// Obtain the current page HTML string
string currentPageHtmlString = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the current page HTML string a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(currentPageHtmlString, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Current_Page.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
else
{
base.Render(writer);
}
}

Categories