2018年5月8日火曜日

透明テキストを持つ PDF を作成するには

サンプルコードです。重要なのは SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE) を指定することで、普通に ShowTextAligned で良いようです。

 using (var fs = File.Create(@"C:\A\A.pdf"))
 {
  Rectangle A4 = new Rectangle(0, 0, 595.44f, 841.68f);
  Rectangle A4R = new Rectangle(0, 0, 841.68f, 595.44f);
  var document = new Document(A4R);
  var writer = PdfWriter.GetInstance(document, fs);
  document.Open();
  var appender = writer.DirectContent;

  // http://www.plusism.biz/blog/2013/12/14/2
  FontFactory.Register(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "msgothic.ttc"));

  var font = iTextSharp.text.FontFactory.GetFont("MS-UIGothic", BaseFont.IDENTITY_H, 40f);

  appender.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
  appender.SetFontAndSize(font.GetCalculatedBaseFont(false), 40f);
  appender.BeginText();
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "1", 40, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "2", 60, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "3", 80, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "A", 100, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "B", 120, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "C", 140, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "あ", 160, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "い", 200, 40, 0);
  appender.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "う", 240, 40, 0);
  appender.EndText();
  document.Close();
  writer.Close();
 }