ITextSharpにHTMLをPDFに変換する機能があるかどうか知りたいのですが。変換するものはすべてプレーンテキストになりますが、残念ながらITextSharpに関するドキュメントはほとんどまたはまったくないため、それが実行可能なソリューションになるかどうかを判断できません。
それができない場合、誰かが私に、単純なプレーンテキストのHTMLドキュメントを取得してPDFに変換できるいくつかの優れた無料の.netライブラリを教えてもらえますか?
ティア。
ITextSharpにHTMLをPDFに変換する機能があるかどうか知りたいのですが。変換するものはすべてプレーンテキストになりますが、残念ながらITextSharpに関するドキュメントはほとんどまたはまったくないため、それが実行可能なソリューションになるかどうかを判断できません。
それができない場合、誰かが私に、単純なプレーンテキストのHTMLドキュメントを取得してPDFに変換できるいくつかの優れた無料の.netライブラリを教えてもらえますか?
ティア。
私は数週間前に同じ質問に出くわしました、そしてこれは私が見つけたものからの結果です。このメソッドは、HTMLをPDFにすばやくダンプします。ドキュメントには、おそらく何らかのフォーマットの調整が必要になります。
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
いくつか掘り下げた後、ITextSharpで必要なことを達成するための良い方法を見つけました。
将来誰かに役立つ場合のサンプルコードを次に示します。
protected void Page_Load(object sender, EventArgs e)
{
Document document = new Document();
try
{
PdfWriter.GetInstance(document, new FileStream("c:\\my.pdf", FileMode.Create));
document.Open();
WebClient wc = new WebClient();
string htmlText = wc.DownloadString("http://localhost:59500/my.html");
Response.Write(htmlText);
List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
document.Close();
}
catch
{
}
}
これが、バージョン5.4.2(nugetインストールから)で作業して、asp.netmvcコントローラーからpdf応答を返すことができたものです。必要に応じて、出力にMemoryStreamの代わりにFileStreamを使用するように変更できます。
これは、html-> pdf変換の現在のiTextSharpの使用法の完全な例であるため、ここに投稿します(画像を無視しますが、使用法では必要ないため、これは確認していません)。
iTextSharpのXmlWorkerHelperを使用するため、着信hmtlは有効なXHTMLである必要があるため、入力によっては修正が必要になる場合があります。
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System.IO;
using System.Web.Mvc;
namespace Sample.Web.Controllers
{
public class PdfConverterController : Controller
{
[ValidateInput(false)]
[HttpPost]
public ActionResult HtmlToPdf(string html)
{
html = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<!DOCTYPE html
PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN""
""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">
<head>
<title>Minimal XHTML 1.0 Document with W3C DTD</title>
</head>
<body>
" + html + "</body></html>";
var bytes = System.Text.Encoding.UTF8.GetBytes(html);
using (var input = new MemoryStream(bytes))
{
var output = new MemoryStream(); // this MemoryStream is closed by FileStreamResult
var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 50, 50, 50, 50);
var writer = PdfWriter.GetInstance(document, output);
writer.CloseStream = false;
document.Open();
var xmlWorker = XMLWorkerHelper.GetInstance();
xmlWorker.ParseXHtml(writer, document, input, null);
document.Close();
output.Position = 0;
return new FileStreamResult(output, "application/pdf");
}
}
}
}
評判があれば、mightymadaの答えを1つ上げたいと思います。Pechkinを使用してasp.netHTMLからPDFへのソリューションを実装しただけです。結果は素晴らしいです。
Pechkin用のnugetパッケージがありますが、上記のポスターが彼のブログ(http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/ )で言及しているように、彼女が気にしないことを願っています私はそれを再投稿します)、このブランチで修正されたメモリリークがあります:
https://github.com/tuespetre/Pechkin
上記のブログには、このパッケージを含める方法に関する具体的な手順が記載されています(32ビットdllであり、.net4が必要です)。これが私のコードです。着信HTMLは、実際にはHTML Agilityパックを介してアセンブルされます(請求書の生成を自動化しています)。
public static byte[] PechkinPdf(string html)
{
//Transform the HTML into PDF
var pechkin = Factory.Create(new GlobalConfig());
var pdf = pechkin.Convert(new ObjectConfig()
.SetLoadImages(true).SetZoomFactor(1.5)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true), html);
//Return the PDF file
return pdf;
}
繰り返しになりますが、mightymadaに感謝します-あなたの答えは素晴らしいです。
自明ではないHTML(CSSクラスもある)を変換できるので、Pechkinと呼ばれる別のライブラリを使用することを好みます。これが可能なのは、このライブラリがChromeやSafariなどのブラウザでも使用されているWebKitレイアウトエンジンを使用しているためです。
Pechkinでの私の経験をブログで詳しく説明しました:http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/
上記のコードは確かにHTMLをPDFに変換するのに役立ちますが、HTMLコードに相対パスを持つIMGタグがある場合は失敗します。iTextSharpライブラリは、相対パスを絶対パスに自動的に変換しません。
上記のコードを試し、IMGタグも処理するコードを追加しました。
参考のためにここにコードがあります:http: //www.am22tech.com/html-to-pdf/
HTMLファイルをPDFに変換する機能があります。
変換に必要な名前空間は次のとおりです。
using iTextSharp.text;
using iTextSharp.text.pdf;
変換とダウンロードファイルの場合:
// Create a byte array that will eventually hold our final PDF
Byte[] bytes;
// Boilerplate iTextSharp setup here
// Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream())
{
// Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
using (var doc = new Document())
{
// Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms))
{
// Open the document for writing
doc.Open();
string finalHtml = string.Empty;
// Read your html by database or file here and store it into finalHtml e.g. a string
// XMLWorker also reads from a TextReader and not directly from a string
using (var srHtml = new StringReader(finalHtml))
{
// Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
doc.Close();
}
}
// After all of the PDF "stuff" above is done and closed but **before** we
// close the MemoryStream, grab all of the active bytes from the stream
bytes = ms.ToArray();
}
// Clear the response
Response.Clear();
MemoryStream mstream = new MemoryStream(bytes);
// Define response content type
Response.ContentType = "application/pdf";
// Give the name of file of pdf and add in to header
Response.AddHeader("content-disposition", "attachment;filename=invoice.pdf");
Response.Buffer = true;
mstream.WriteTo(Response.OutputStream);
Response.End();
2020年の更新:
HTMLからPDFへの変換は今では非常に簡単です。NuGetを使用してitex7とitex7.pdfhtmlをインストールするだけです。Visual Studioでこれを行うには、[プロジェクト]>[NuGetパッケージの管理...]に移動します。
この依存関係を必ず含めてください。
using iText.Html2pdf;
これで、文字通りこの1つのライナーを貼り付けるだけで、完了です。
HtmlConverter.ConvertToPdf(new FileInfo(@"temp.html"), new FileInfo(@"report.pdf"));
この例をVisualStudioで実行している場合は、htmlファイルが/bin/Debug
ディレクトリにあるはずです。
興味のある方は、こちらのリソースをご覧ください。また、itex7はAGPLの下でライセンスされていることに注意してください。
htmlサーバー側でhtmlをpdfに変換する場合は、Rotativaを使用できます。
Install-Package Rotativa
これはwkhtmltopdfに基づいていますが、iTextSharpよりも優れたcssサポートがあり、ビューをpdfとして返すことができるため、MVC(主に使用されます)との統合が非常に簡単です。
public ActionResult GetPdf()
{
//...
return new ViewAsPdf(model);// and you are done!
}