LoginSignup
9

More than 5 years have passed since last update.

HTMLをPDFに変換する方法

Posted at

PDFをHTMLに変換することは、ほとんどすべての個人またはグループとしてPDFファイルを安全に配布または共有するための最良の形式です。それからHTMLをPDFに簡単に変換して安全にするべきです。この記事では、HTMLのURLをPDFとHTMLの文字列をPDFに変換する方法を示します。

使用ツール: Spire.PDF for .NET 5.1

HTML URLをPDFまで:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.Widget;
using Spire.Pdf.Fields;
using System.Threading;
using Spire.Pdf.HtmlConverter;

namespace PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //作成するPdfDocument実例
            PdfDocument doc = new PdfDocument();
            //ページのレイアウトを設定      
            PdfPageSettings setting = new PdfPageSettings();
            setting.Size = new SizeF(1000,1000);
            setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
            htmlLayoutFormat.IsWaiting = true;
            //HTMLのURL
            String url = "https://www.wikipedia.org/";
            Thread thread = new Thread(() =>
            { doc.LoadFromHTML(url, false, false, false, setting,htmlLayoutFormat); });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            //PDFファイルを保存します
            doc.SaveToFile("output-wiki.pdf");
        }
    }
}

convert-HTML-into-PDF.png

HTML文字列をPDFに変換する

//作成するPdfDocument実例
PdfDocument pdf = new PdfDocument();
//ページのレイアウトを設定      
PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
//ロードを待っていない
htmlLayoutFormat.IsWaiting = false;
PdfPageSettings setting = new PdfPageSettings();
setting.Size = PdfPageSize.A4;
// HTMLコードをロードする
string htmlCode = File.ReadAllText("C:\\..\\e-iceblue.html");

    Thread thread = new Thread(() =>
    { pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
thread.Join();
// PDFファイルを保存します
pdf.SaveToFile("sample.pdf");

HTML string to PDF.png

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9