For a simple reciept system I need to somehow define a template document with simple formatting, fill it with data and print it on a standard windows printer. It has to work on a windows service. What technology should I best use?
EDIT:
I tried using PDF-Forms. I defined a couple of text boxes and filled them in with iTextSharp. It worked until the point where I had to print them, which is really hard, as you have to essentially use the reader executable directly.
An alternative which seems to be better integrated into .NET seems to be to use XPS. Does XPS provide a similar functionality?
Create your own receipt template using html or plain text.
Example using html:
HTML
<html>
<head>
<title>Receipt</title>
</head>
<body>
<div>The price: <%Price%></div>
<div>The time: <%Time%></div>
<div>Payment Method: <%PaymentMethod%></div>
</body>
</html>
C#
static void Main(string[] args)
{
CreateReceipt("€1.50", "09.30", "Cash");
}
private static void CreateReceipt(string price, string time, string paymentMethod)
{
string bodyFile;
string template = System.IO.Directory.GetCurrentDirectory() + "\\template.html";
using (StreamReader reader = new StreamReader(template))
{
bodyFile = reader.ReadToEnd();
bodyFile = bodyFile.Replace("<%Price%>", price);
bodyFile = bodyFile.Replace("<%Time%>", time);
bodyFile = bodyFile.Replace("<%PaymentMethod%>", paymentMethod);
}
FileStream fs = File.OpenWrite(System.IO.Directory.GetCurrentDirectory() + "\\receipt.html");
StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
writer.Write(bodyFile);
writer.Close();
}
}
Use Mustache to create HTML templates and populate them.
The .Net interfaces are very easy to use.
Once you've got the HTML, you can use a WebBrowser control - offscreen - to print.
There are various ways;
Create a text file and search and replace keywords with appropriate values. Save/Print this.
Create a html file and search and replace keywords with appropriate values. Save/Print this.
Create a PDF file with built-in fields and replace these with appropriate values. Save/Print this.
And more...
Just for an Idea if you haven't seen this, You can print HTML DIV
How do I print part of a rendered HTML page in JavaScript?
You could try ActiveReports
Link to ComponentOne
It's not for free.. but it works for printing stuff as you wish.
Just create Templates and embedd them in your code.
We endet up using the format of the EPSON TM-Intelligent series.
Related
I want to add a header and a footer, which becomes repeated, to my PDF which becomes created by iText7 by converting the HTML.
However, all examples I found so far on the internet describes how to create a blank PDF by code with header and footer.
Does anybody know how I can achive this? I already tried to use the CSS print media queries to specify some areas but it seems those are ignored by iText7.
The conversion is really simple:
string input = "Bestellung.html";
string output = "Bestellung.pdf";
HtmlConverter.ConvertToPdf(new FileInfo(input), new FileInfo(output));
bestellung.html is just a plain HTML file with some demo content.
See mediaDeviceDescription under ConverterProperties.
If your input file uses this feature, then you can simply tell pdfHTML
to interpret the relevant set of rules:
ConverterProperties props = new ConverterProperties();
props.setMediaDeviceDescription(new
MediaDeviceDescription(MediaType.PRINT));
Then you call the method with this signature:
static void convertToPdf(InputStream htmlStream, PdfDocument pdfDocument, ConverterProperties converterProperties)
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.
I'm trying to create an application that converts a file from the HTML format to the PDF format.
The approach I am using is:
HTML to XHTML
XHTML to Formatting Object
Formatting Object to PDF
I'm having a bit of trouble with the whole XHTML to FO(or xsl).
Can you please tell me how to transform the XHTML to FO?
Or maybe a different approapch to the whole HTML to PDF?
Thanks, Catalin
I have write easiest way to write html to pdf code using NRerco Pdf library which available free, Install nuget package
PM > Install-Package NReco.PdfGenerator
Create HtmltoPdf()
{
if (System.IO.File.Exists("HTMLFile.html"))
{
System.IO.File.Delete("HTMLFile.html");
}
System.IO.File.WriteAllText("HTMLFile.html", html);
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
if (System.IO.File.Exists("export.pdf"))
{
System.IO.File.Delete("export.pdf");
}
htmlToPdf.GeneratePdfFromFile("HTMLFile.html", null, "export.pdf");
}
Well you could use a HTML to PDF converter via shell, I am sorry I can not rememeber the name of the one I have used in the past, if you have a Google around, you should be able to find a good one.
Searched a lot for my personal stack app project SO2PDF and finally settled with wkhtmltopdf which so far is the best free tool to convert HTML to PDF. Yes I used it with c# ;-)
Here is the different approach. We are going to convert HTML/XML to PDF directly with 3d party tool (it has multiple preference and settings of conversion and doesn't require any external libraries).
1) Download free HTML to PDF SDK from her (it is easy PDF SDK)
2) Use the following code or run Action Center to customize the conversion
using BCL.easyPDF.Printer;
namespace TestPrinter
{
class Program
{
static void Main(string[] args)
{
if(args.Length != 2)
return;
string inputFileName = args[0];
string outputFileName = args[1];
Printer printer = new Printer();
try
{
IEPrintJob printjob = printer.IEPrintJob;
printjob.PrintOut(inputFileName, outputFileName);
}
catch(PrinterException ex)
{
System.Console.WriteLine(ex.Message);
}
finally
{
printer.Dispose();
}
}
}
}
Image: HTML to PDF C# API - Action Center
I want to output my InnerXml property for display in a web page. I would like to see indentation of the various tags. Is there an easy way to do this?
Here's a little class that I put together some time ago to do exactly this.
It assumes that you're working with the XML in string format.
public static class FormatXML
{
public static string FormatXMLString(string sUnformattedXML)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(sUnformattedXML);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = null;
try
{
xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xd.WriteTo(xtw);
}
finally
{
if(xtw!=null)
xtw.Close();
}
return sb.ToString();
}
}
You should be able to do this with code formatters. You would have to html encode the xml into the page first.
Google has a nice prettifyer that is capable of visualizing XML as well as several programming languages.
Basically, put your XML into a pre tag like this:
<pre class="prettyprint">
<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>
</pre>
Use the XML Web Server Control to display the content of an xml document on a web page.
EDIT: You should pass the entire XmlDocument to the Document property of the XML Web Server Control to display it. You don't need to use the InnerXml property.
If identation is your only cocern and if you can afford to launch xternall process, you can process xml file with HTML Tidy console tool (~100K).
The code is:
tidy --input-xml y --output-xhtml y --indent "1" $(FilePath)
Then you can display idented string on web page once you get rid of special chars.
It would be also easy to create recursive function that makes such output - simply iterate nodes starting from the root and enter next recursion step for child node, passing identation as a parameter to each new recursion call.
Check out the free Actipro CodeHighlighter for ASP.NET - it can neatly display XML and other formats.
Or are you more interested in actually formatting your XML? Then have a look at the XmlTextWriter - you can specify things like Format (indenting or not) and the indent level, and then write out your XML to e.g. a MemoryStream and read it back from there into a string for display.
Marc
Use an XmlTextWriter with the XmlWriterSettings set up so that indentation is enabled. You can use a StringWriter as "temporary storage" if you want to write the resulting string onto screen.
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.