I am trying to convert HTML to PDF with iTextSharp
in MVC Razor, but everything I have tried has not worked. Does anyone know how to accomplish this?
问题:
回答1:
There's a detailed and step-by-step tutorial
on CodeProject you might follow. It illustrates how you could serve an ASP.NET MVC View as PDF file using iTextSharp for the conversion. Bear in mind though that iTextSharp was not meant for converting HTML to PDF so it might not cope very well with complex HTML pages and CSS styles.
回答2:
Here is how you implement this solution using the Razor engine NOT with the weird <itext..
markup.
This way you have full control over the pdf presentation using standard html output.
The project with an example solution and source code is available here with nuget installation instructions:
https://github.com/andyhutch77/MvcRazorToPdf
Install-Package MvcRazorToPdf
This also uses the new itextsharp licence, so does not suffer from any of the negatives mentioned in the other answers.
回答3:
You should check out RazorPDF which is using iText to generate the PDF, but in a friendlier way.
回答4:
public virtual void printpdf(string html)
{
String htmlText = html.ToString();
Document document = new Document();
string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+Filename+".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();
}
just pass html string
in to parameter
that string you will get by renderpartialview text = viewname....
回答5:
A good way to convert from MVC HTML View to PDF (even if it's not directly on the subject regarding iTextSharp) is using Rotativa :
Install-Package Rotativa
This is based on wkhtmltopdf
but it has better css support than iTextSharp has and is very simple to integrate with MVC as you can simply return the view as pdf:
public ActionResult GetPdf()
{
//...
return new ViewAsPdf(model);// and you are done!
}
回答6:
Here is a complete example for MVC Razor in C# using the evo html to pdf for .net to convert the current MVC view to PDF and send the resulted PDF to browser for download:
[HttpPost]
public ActionResult ConvertCurrentPageToPdf(FormCollection collection)
{
object model = null;
ViewDataDictionary viewData = new ViewDataDictionary(model);
// The string writer where to render the HTML code of the view
StringWriter stringWriter = new StringWriter();
// Render the Index view in a HTML string
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Index", null);
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
viewData,
new TempDataDictionary(),
stringWriter
);
viewResult.View.Render(viewContext, stringWriter);
// Get the view HTML string
string htmlToConvert = stringWriter.ToString();
// Get the base URL
String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Convert_Current_Page/ConvertCurrentPageToPdf".Length);
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Convert the HTML string to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);
// Send the PDF file to browser
FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
fileResult.FileDownloadName = "Convert_Current_Page.pdf";
return fileResult;
}
回答7:
here you can find a different approach in case you want to write plain xml, i find it much simpler and lighter.
http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3
回答8:
This is how to do it using MVC
:
[Route("ABCDD")]
[HttpGet]
public void ABCDD() {
WebClient wc = new WebClient();
// string url = HttpContext.Current.Request.Url.AbsoluteUri;
string url = "http://localhost:3042/Reports/COAListing";
string fileContent = wc.DownloadString(url);
List<string> tableContents = GetContents(fileContent, table_pattern);
string HTMLString = String.Join(" ", tableContents.ToArray());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(new Paragraph("Welcome to dotnetfox"));
List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(HTMLString), null);
for (int k = 0; k < htmlarraylist.Count; k++) {
pdfDoc.Add((IElement) htmlarraylist[k]);
}
pdfDoc.Close();
HttpContext.Current.Response.ContentType = "pdf/application";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;" +
"filename=sample.pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Write(pdfDoc);
HttpContext.Current.Response.End();
}
回答9:
In case you are using ASP.NET Core and iTextSharp is not that important to you here is my solution using PhantomJS: http://nikolay.it/Blog/2018/03/Generate-PDF-file-from-Razor-view-using-ASP-NET-Core-and-PhantomJS/37
Get HTML string from a Razor view
This step is pretty straight-forward. There is a service called IRazorViewEngine
in ASP.NET Core which can be injected and then used to get the view. After providing the view with default ViewDataDictionary
and ActionContext
we can request the view to be rendered into StringWriter
which can be easily converted to string. Here is ready-to-use code for getting a string from given Razor view file:
public interface IViewRenderService
{
Task<string> RenderToStringAsync(string viewName, object model);
}
public class ViewRenderService : IViewRenderService
{
private readonly IRazorViewEngine razorViewEngine;
private readonly ITempDataProvider tempDataProvider;
private readonly IServiceProvider serviceProvider;
public ViewRenderService(
IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
this.razorViewEngine = razorViewEngine;
this.tempDataProvider = tempDataProvider;
this.serviceProvider = serviceProvider;
}
public async Task<string> RenderToStringAsync(string viewName, object model)
{
var httpContext = new DefaultHttpContext { RequestServices = this.serviceProvider };
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
using (var sw = new StringWriter())
{
var viewResult = this.razorViewEngine.GetView(null, viewName, false);
if (viewResult.View == null)
{
throw new ArgumentNullException($"{viewName} does not match any available view");
}
var viewDictionary =
new ViewDataDictionary(
new EmptyModelMetadataProvider(),
new ModelStateDictionary()) { Model = model };
var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, this.tempDataProvider),
sw,
new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
return sw.ToString();
}
}
}
One important think here: if you use view compilation (pre-compiling views to YourProject.Web.PrecompiledViews.dll
) then it is important to get the view using the GetView
method instead of FindView
. More information here.
Generate the PDF file from HTML using PhantomJS
For this task we are going to use a headless browser which will render the HTML (with all CSS and JS included in it). There are many such tools but I will use PhantomJS (headless WebKit scriptable with a JavaScript API). PhantomJS can save the rendered page to small-sized PDF pretty fast. For the PDF export to work we are going to need a .js
file which will use the PhantomJS API to tell the tool that we want to export the file:
"use strict";
var page = require('webpage').create(),
system = require('system'),
address,
output;
console.log('Usage: rasterize.js [URL] [filename] [paperformat]');
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
page.paperSize = { format: system.args[3], orientation: 'portrait', margin: '0.5cm' };
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
The next thing is to run the phantomjs.exe
process and pass the rasterize.js
file along with paths for the HTML file and the output file name for the PDF result. This is done in HtmlToPdfConverter.cs
:
public interface IHtmlToPdfConverter
{
byte[] Convert(string htmlCode);
}
public class HtmlToPdfConverter : IHtmlToPdfConverter
{
public byte[] Convert(string htmlCode)
{
var inputFileName = "input.html";
var outputFileName = "output.pdf";
File.WriteAllText(inputFileName, htmlCode);
var startInfo = new ProcessStartInfo("phantomjs.exe")
{
WorkingDirectory = Environment.CurrentDirectory,
Arguments = string.Format(
"rasterize.js \"{0}\" {1} \"A4\"",
inputFileName,
outputFileName),
UseShellExecute = true,
};
var process = new Process { StartInfo = startInfo };
process.Start();
process.WaitForExit();
var bytes = File.ReadAllBytes(outputFileName);
File.Delete(inputFileName);
File.Delete(outputFileName);
return bytes;
}
}
If you are going to deploy your application in Azure it is important to have UseShellExecute
set to true
.
Use the code together
Since we now have implemented both IViewRenderService
and IHtmlToPdfConverter
we can start using them by first register them in the Startup.cs
file where your ConfigureServices method should be located (services.AddScoped<IViewRenderService, ViewRenderService>()
and services.AddScoped<IHtmlToPdfConverter, HtmlToPdfConverter>()
). Now lets see the code wrapped up together:
private readonly IViewRenderService viewRenderService;
private readonly IHtmlToPdfConverter htmlToPdfConverter;
public DashboardController(
IViewRenderService viewRenderService,
IHtmlToPdfConverter htmlToPdfConverter)
{
this.viewRenderService = viewRenderService;
this.htmlToPdfConverter = htmlToPdfConverter;
}
[HttpGet]
public async Task<IActionResult> GetPdf(SomeInputModel input)
{
var model = this.GetViewModel(input);
var htmlData = await this.viewRenderService.RenderToStringAsync("~/Views/Dashboard/GetPdf.cshtml", model);
var fileContents = this.htmlToPdfConverter.Convert(htmlData);
return this.File(fileContents, "application/pdf");
}