C# - Save XML file as PDF as Raw Image (not converting) - c#

I am trying to save xml file as PDF as it is. In other words, I am trying to create PDF file that shows content of XML like a screenshot (like raw screenshot). My client somehow needs it like this. I couldn't really find the same question on stackoverflow. Is there anyway I can do this using iText or some other library?
Thank you!

First extract your text from XML file:
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
string myText;
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
myText= node.InnerText; //or loop through its children as well
}
Then create a PDF file and pass this text into it
in this case here I use PDFFlow library to create pdf documents
var DocumentBuilder.New()
.AddSection().AddParagraphToSection(myText).ToDocument()
.Build("Result.PDF");

If you load the xml in a browser you can easily save to searchable PDF
In a shell call (replace msedge with chrome if necessary)
"path to\msedge.exe" --headless --disable-gpu --print-to-pdf="out path\xml.pdf" --enable-logging "file://path to A\file.xml"
Enable logging helps as it can take a long time to process without any visual progress.
[0818/231038.640:INFO:headless_shell.cc(648)] Written to file ...\xml.pdf.
You can also add --print-to-pdf-no-header. Also if adding some style consider --run-all-compositor-stages-before-draw but I have no idea if that works for xml.
ForGet Image --screenshot as a 40 Page high XML as JPEG does NOT translate well to PDF. I tried :-)
If you want that as an image PDF then Re-Print the PDF to PDF using a command line viewer such as this since it is ONLY Print As Image output :-) also note it can in addition read the XML in Black and White (NO linting).
But have not tested how well it does XML2PDF via command line print
SumatraPDF -print-to "My Print to PDF" "path to\filename.pdf" (or xml in mono)
Note "My Print to PDF" is a promptless port you need to configure as required.

Related

C# - Save XML's plain text as PDF instead of converting [duplicate]

I am trying to save xml file as PDF as it is. In other words, I am trying to create PDF file that shows content of XML like a screenshot (like raw screenshot). My client somehow needs it like this. I couldn't really find the same question on stackoverflow. Is there anyway I can do this using iText or some other library?
Thank you!
First extract your text from XML file:
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
string myText;
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
myText= node.InnerText; //or loop through its children as well
}
Then create a PDF file and pass this text into it
in this case here I use PDFFlow library to create pdf documents
var DocumentBuilder.New()
.AddSection().AddParagraphToSection(myText).ToDocument()
.Build("Result.PDF");
If you load the xml in a browser you can easily save to searchable PDF
In a shell call (replace msedge with chrome if necessary)
"path to\msedge.exe" --headless --disable-gpu --print-to-pdf="out path\xml.pdf" --enable-logging "file://path to A\file.xml"
Enable logging helps as it can take a long time to process without any visual progress.
[0818/231038.640:INFO:headless_shell.cc(648)] Written to file ...\xml.pdf.
You can also add --print-to-pdf-no-header. Also if adding some style consider --run-all-compositor-stages-before-draw but I have no idea if that works for xml.
ForGet Image --screenshot as a 40 Page high XML as JPEG does NOT translate well to PDF. I tried :-)
If you want that as an image PDF then Re-Print the PDF to PDF using a command line viewer such as this since it is ONLY Print As Image output :-) also note it can in addition read the XML in Black and White (NO linting).
But have not tested how well it does XML2PDF via command line print
SumatraPDF -print-to "My Print to PDF" "path to\filename.pdf" (or xml in mono)
Note "My Print to PDF" is a promptless port you need to configure as required.

How to convert docx to html file using open xml with formatting

I know there are lot of question having same title but I am currently having some issue for them I didn't get the correct way to go.
I am using Open xml sdk 2.5 along with Power tool to convert .docx file to .html file which uses HtmlConverter class for conversion.
I am successfully able to convert the docx file into the Html file but the problem is, html file doesn't retain the original formatting of the document file. eg. Font-size,color,underline,bold etc doesn't reflect into the html file.
Here is my existing code:
public void ConvertDocxToHtml(string fileName)
{
byte[] byteArray = File.ReadAllBytes(fileName);
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(byteArray, 0, byteArray.Length);
using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
{
HtmlConverterSettings settings = new HtmlConverterSettings()
{
PageTitle = "My Page Title"
};
XElement html = HtmlConverter.ConvertToHtml(doc, settings);
File.WriteAllText(#"E:\Test.html", html.ToStringNewLineOnAttributes());
}
}
}
So I just want to know if is there any way by which I can retain the formatting in converted HTML file.
I know about some third party APIs which does the same thing. But I would prefer if there any way using open xml or any other open source to do this.
PowerTools for Open XML just released a new HtmlConverter module. It now contains an open source, free implementation of a conversion from DOCX to HTML formatted with CSS. The module HtmlConverter.cs supports all paragraph, character, and table styles, fonts and text formatting, numbered and bulleted lists, images, and more. See https://openxmldeveloper.org/
Your end result will not look exactly the way your Word Document turns out, but this link might help.
You might want to find an external tool to help you do this, like Aspose Words
You can use OpenXML Viewer extension for Firefox for Converting with formatting.
http://openxmlviewer.codeplex.com
This works for me. Hope this helps.

WPF WebBrowser - built-in search dialog doesn't work if content was loaded with NavigateToString

I use WebBrowser to display generated XML. My XML string loaded into browser by call to NavigateToString:
var text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ Environment.NewLine
+ "<whatever/>";
Browser.NavigateToString(text);
After browser loads string content I'm trying to search for any displayed text using standard Ctrl+F search dialog - but it always shows warning "No matches found".
If I save the XML string to a file and use Browser.Navigate(filename) it works.
Any ideas?
When you navigate to a file, the WebBrowser control performs MIME-type sniffing (often using the file extension as a hint). Then it creates an Active Document object of the corresponding type. Most often it's an instance of MSHTML Document, but can also be an XML, PDF or Word document, all of which support Active Document interfaces.
Now, when you navigate to a string with NavigateToString, the WebBrowser doesn't make any attempts to recognize the document type, and simply creates and instance of MSHTML Document (rather than XML Document), then tries to parse the content as HTML and fails.
I don't think you can get the desired behavior using NavigateToString, and I believe the same applies to NavigateToStream. To illustrate what's going on, take your XML content and save it as filename.html, filename.txt and filename.xml. Try opening each file with IE.
On a side note, when you navigate to a URL, the server actually has an option to suggest the MIME type, using HTTP headers. The browser may or may not tolerate such suggestion (it will still perform some validation checks).
The bottom line: you will not be able to render XML with NavigateToString or NavigateToStream. You're going to have to convert it to HTML first (e.g., with an XSLT transform).
I just had the same problem.
There is even the possibility to open the xml file directly using the overload:
webbrowser.Navigate(string filepathToXML)
Going this way, the builtin search panel works like a charm.

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.

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

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.

Categories