HTMLからPDFファイルを作成

  • 日本語を使うにはフォントを指定する。
  • フォントを指定するにはFontProviderを作る。
 static void Main(string[] args)
 {
     Font fnt = new Font(BaseFont.CreateFont(@"c:\windows\fonts\msgothic.ttc,0", BaseFont.IDENTITY_H, true), 40);
 
     Dictionary< string, object > dicProvider = new Dictionary<string, object>();
     dicProvider.Add(HTMLWorker.FONT_PROVIDER, new NewFontProvider());
 
     string html = "<html><body><h1>Test PDF</h1><ul><li>あいうえお</li><li>xyz</li></ul></body></html>";
 
     string outfilepath = @"c:\tmp\test-html.pdf";
     FileStream fsoutput = new FileStream(outfilepath, FileMode.Create);
     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, fsoutput);
 
     // step 3: we create a worker parse the document
     HTMLWorker worker = new HTMLWorker(document);
     worker.SetProviders(dicProvider);
 
     // 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();
 
     Console.ReadLine();
 }
 
 public class NewFontProvider : FontFactoryImp
 {
     public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
     {
         if (string.IsNullOrEmpty(fontname)) {
             fontname = "c:\\windows\\fonts\\msmincho.ttc,0";
             encoding = BaseFont.IDENTITY_H;
             embedded = BaseFont.EMBEDDED;
         }
 
         return base.GetFont(fontname, encoding, embedded, size, style, color, cached);
     }
 }

参考


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS

Last-modified: 2014-04-04 (金) 14:03:15