2014年12月21日 星期日

健保e化抽審-4(PDF加入浮水印)

怕有日後資料外流不易追查,進而引發不必要的資安議題(申請單都消化不完了,還要搞這個),所以還是小心點好,在PDF檔裡加入浮水印好了,避免有心人傳來傳去。 必要時還可以加入當初使用者是誰,方便源頭的追蹤管理。
private void button19_Click(object sender, EventArgs e)
{
  string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.System)   @"\..\Fonts\kaiu.ttf";
  BaseFont bfChinese = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    
  string fileBefore = @"C:\temp\fileBefore.pdf";
  string fileAfter = @"C:\temp\fileAfter.pdf";

  // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
  using (PdfReader reader = new PdfReader(fileBefore))
  // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
  using (FileStream fs = new FileStream(fileAfter, FileMode.Create, FileAccess.Write, FileShare.None))
  using (PdfStamper stamper = new PdfStamper(reader, fs))
  {
    // Getting total number of pages of the Existing Document
    int pageCount = reader.NumberOfPages;

    // Create New Layer for Watermark
    PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);

    // Loop through each Page
    for (int pageNum = 1; pageNum <= pageCount; pageNum  )
    {
      // Getting the Page Size
      iTextSharp.text.Rectangle rect = reader.GetPageSize(pageNum);

      // Get the ContentByte object
      PdfContentByte cb = stamper.GetUnderContent(pageNum);
   
      // Tell the cb that the next commands should be "bound" to this new layer
      cb.BeginLayer(layer);
      cb.SetFontAndSize(bfChinese, 50);
      cb.SetColorFill(BaseColor.BLACK);

      PdfGState gState = new PdfGState();
      gState.FillOpacity = 0.25f;
      cb.SetGState(gState);

      cb.BeginText();
      cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "僅供健保e化抽審使用", rect.Width / 2, rect.Height / 2, 45f);
      cb.EndText();

      // Close the layer
      cb.EndLayer();
    }
  }
}
參考資料
[1] Adding Watermark to PDF Document using Layer
[2] Nested using statements in C#

沒有留言:

張貼留言