123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using Netca_PDFSign_COM;
- using System.IO;
- using System.Drawing;
- using Spire.Pdf;
- using System.Text;
- using Spire.Pdf.Graphics;
- namespace EmisTerminal
- {
- public class PDFSign
- {
- public const string PDFPath = "~/Content/PrintFile";
- public static string PDFAbsolutePath
- {
- get
- {
- return HttpContext.Current.Server.MapPath(PDFPath);
- }
- }
- static PDFSign()
- {
- if (!Directory.Exists(PDFAbsolutePath))
- {
- Directory.CreateDirectory(PDFAbsolutePath);
- }
- }
- private byte[] GetImage(string certEncoded)
- {
- if (!string.IsNullOrEmpty(certEncoded))
- {
- IUtilTool util = new UtilTool();
- byte[] imgBytes = util.GetImageFromDevicByCert(certEncoded);
- if (imgBytes == null)
- {
- throw new Exception("找不到可用的签章图片!");
- }
- return imgBytes;
- }
- else
- {
- throw new Exception("找不到可用的外观,请确定已连接设备!");
- }
- }
- public string Sign(string targetFileName, Stream pageStream)
- {
- var pageBytes = new byte[pageStream.Length];
- var monthString = DateTime.Today.ToString("yyyy-MM");
- var monthPath = PDFAbsolutePath + @"\" + monthString;
- if (!Directory.Exists(monthPath))
- {
- Directory.CreateDirectory(monthPath);
- }
- var destFileName = "";
- var printTimes = Directory.GetFiles(monthPath).Where(x => x.Contains(targetFileName)).ToArray();
- if (printTimes.Length > 0)
- {
- destFileName = targetFileName + "(" + (printTimes.Length).ToString() + ").pdf";
- }
- else
- {
- destFileName = targetFileName + ".pdf";
- }
- var destFilePath = monthPath + @"\" + destFileName;
- pageStream.Read(pageBytes, 0, pageBytes.Length);
- ISignatureCreator creator = new SignatureCreator();
- var certEncoded = creator.SelectCert(null, 0);
- creator.SetSignPDFBytes(pageBytes, null);
- var pageCount = creator.GetPagesCount();
- var imgBytes = this.GetImage(certEncoded);
- MemoryStream ms = new MemoryStream(imgBytes);
- Image image = Image.FromStream(ms);
- PdfDocument pdf = new PdfDocument(pageStream);
- creator.SetSignCert(certEncoded, "sha-256", Const.NATCA_PASSWORD);
- for (int i = 1; i <= pageCount; i++)
- {
- try
- {
- var position = pdf.Pages[i - 1].FindAllText().Finds.OrderByDescending(x => x.Bounds.Bottom).First().Bounds;
- creator.SealPosition(destFilePath, i, Convert.ToInt32(Math.Floor(position.X - 20)), Convert.ToInt32(Math.Floor(position.Y - 99)), 119, 119, null, Convert.ToBase64String(imgBytes));
- }
- catch (Exception)
- {
- }
- }
- var destPath = PDFPath + "/" + monthString + "/" + destFileName;
- return destPath;
- }
- }
- }
|