HTML转PDF+水印以及PDF+水印

下面代码包含2个功能点

1、HTML转PDF以及加水印

2、PDF加水印


相关dll 在这下载

http://download.csdn.net/detail/qq873113580/9132311

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Winnovative.WnvHtmlConvert;
using Winnovative.WnvHtmlConvert.PdfDocument;

namespace Zemp.Process.Util.HtmlPdfConvert
{
    public class HtmlPdfConvertUtil
    {
        /// 
        /// PDF加水印
        /// 
        /// PDF地址(/xxxx/xxxx/xx)
        /// 水印路径
        /// 保存地址
        /// 
        public static string PdfAddWaterMark(string pafPath, string strImagePath, string attachmentDirectoryName = "GenerationPDF")
        {
          

            pafPath = System.Web.HttpContext.Current.Server.MapPath("~" + pafPath);
            ////文件编码
            //Encoding fileEncoding = FileEncodingUtil.GetType(pafPath);
            //文件名
            string serialNumber =  Path.GetFileNameWithoutExtension(pafPath);
            //// 打开文件 
            ////FileStream fileStream = new FileStream(pafPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            //FileStream fileStream = new FileStream(pafPath, FileMode.Open);
           
            //// 读取文件的 byte[] 
            //byte[] bytes = new byte[fileStream.Length];
            //fileStream.Read(bytes, 0, bytes.Length);
            //fileStream.Close();
            //// 把 byte[] 转换成 Stream 
            //Stream stream = new MemoryStream(bytes);
            

           
            //CSS文件路径
            //string strCSSPath = @"\StyleSheet\";
            //PDF保存文件路径
            //string attachmentDirectoryName = "GenerationPDF";
            //生成PDF文件
            string strFileFolder = string.Format(@"\{0}\{1}", attachmentDirectoryName, DateTime.Now.ToString("yyyy-MM-dd").Replace('-', '\\'));
            string strFileName = string.Format(@"\{0}\{1}", attachmentDirectoryName, DateTime.Now.ToString("yyyy-MM-dd").Replace('-', '\\')) + @"\Contract_" + serialNumber + @".pdf";

            //string strImagePath;

            //if (isPreview)
            //    strImagePath = @"\Images\watermark_preview.jpg";
            //else
            //    strImagePath = @"\Images\watermark_new.jpg";

            //string htmlHead = @"PDF文档生成";
            //string htmlTail = @"";

            PdfConverter pdfConverter = new PdfConverter();

            //pdfConverter.LicenseKey = ConfigurationManager.AppSettings["PdfLicenceKey"].ToString();

            //生成PDF文件相关格式设置
            pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
            pdfConverter.PdfDocumentOptions.TopMargin = 50;
            pdfConverter.PdfDocumentOptions.LeftMargin = 50;
            pdfConverter.PdfDocumentOptions.RightMargin = 50;
            pdfConverter.DrawBackground = false;
            pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
            pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
            pdfConverter.PdfStandardSubset = PdfStandardSubset.Full;
            pdfConverter.OptimizePdfPageBreaks = true;


            //PDF文件脚本、页眉、页脚及页码设置
            pdfConverter.PdfDocumentOptions.ShowFooter = true;
            pdfConverter.PdfDocumentOptions.InternalLinksEnabled = true;
            pdfConverter.ScriptsEnabled = false;
            pdfConverter.ScriptsEnabledInImage = false;
            pdfConverter.ScriptsEnabledInImage = false;

            pdfConverter.PdfFooterOptions.FooterHeight = 60;
            pdfConverter.PdfFooterOptions.FooterTextColor = Color.Black;
            pdfConverter.PdfFooterOptions.DrawFooterLine = false;
            pdfConverter.PdfFooterOptions.PageNumberTextFontName = "宋体";
            pdfConverter.PdfFooterOptions.ShowPageNumber = true;
            pdfConverter.PdfFooterOptions.PageNumberingFormatString = @"&p;                                                           ";
            pdfConverter.PdfFooterOptions.PageNumberingStartIndex = 9;
            pdfConverter.PdfFooterOptions.FooterTextFontName = "宋体";
            pdfConverter.PdfFooterOptions.PageNumberYLocation = 15.0f;

            //在服务器端生成PDF文档

            //Winnovative.WnvHtmlConvert.PdfDocument.Document document = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlHead +
            //    contractHTML + htmlTail, System.Web.HttpContext.Current.Server.MapPath("~" + strCSSPath));

            Winnovative.WnvHtmlConvert.PdfDocument.Document document = new Document(pafPath);
            document.TransparencyEnabled = true;

            //取得生成PDF文档对象的第一页,取得页面相关属性
            PdfPage firstPage = document.Pages[0];
            string logoImagePath = System.Web.HttpContext.Current.Server.MapPath("~" + strImagePath);
            ImageElement imageElement = new ImageElement(0, 0, logoImagePath);
            System.Drawing.Image logoImg = System.Drawing.Image.FromFile(logoImagePath);

            //计算用于水印的图片的坐标
            System.Drawing.SizeF imageSizePx = logoImg.PhysicalDimension;
            float imageWidth = UnitsConverter.PixelsToPoints(imageSizePx.Width);
            float imageHeight = UnitsConverter.PixelsToPoints(imageSizePx.Height);
            float templateWidth = firstPage.ClientRectangle.Width + 100;
            float templateHeight = firstPage.ClientRectangle.Height + 100;
            float w = firstPage.PageSize.Width / 4;
            float h = imageHeight / (imageWidth / w);

            //将图片加入到水印模板
            Template watermarkTemplate = document.AddTemplate(new System.Drawing.RectangleF(-60, -50, templateWidth, templateHeight));

            int m = (int)(templateWidth / w) + 1;
            int n = (int)(templateHeight / h) + 1;

            //将图片根据页面的尺寸复制
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    ImageElement watermarkImageElement = new ImageElement((w + 5.0F) * i, h * j, w, h, logoImg);
                    watermarkTemplate.AddElement(watermarkImageElement);
                }
            }

            watermarkTemplate.SendToBackground = true;

            try
            {
                if (!System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~" + strFileFolder)))
                    System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~" + strFileFolder));
                document.Save(System.Web.HttpContext.Current.Server.MapPath("~" + strFileName));
                document.Close();
                return strFileName;
            }
            catch (Exception)
            {
                //Logger.WriteLog("PDF文件生成错误", ex.ToString(), Capital.iWorkflow.Framework.Common.LogPriority.High, Capital.iWorkflow.Framework.Common.EventType.EVENT_ERROR);
                //AlertMessage("PDF文件生成错误!");
                return string.Empty;
            }
            finally
            {
                logoImg.Dispose();
            }
        }
        /// 
        /// 生成PDF文件方法
        /// 
        /// 用于生成PDF文件的HTML内容
        /// 表单流水号(生成的文件名称)
        /// 水印图片地址
        /// 文件保存目录
        /// 返回合同路径
        public static string GeneratePdf(string contractHTML, string serialNumber, string strImagePath, string attachmentDirectoryName = "GenerationPDF")
        {
            //CSS文件路径
            //string strCSSPath = @"\StyleSheet\";
            //PDF保存文件路径
            //string attachmentDirectoryName = "GenerationPDF";
            //生成PDF文件
            string strFileFolder = string.Format(@"\{0}\{1}", attachmentDirectoryName, DateTime.Now.ToString("yyyy-MM-dd").Replace('-', '\\'));
            string strFileName = string.Format(@"\{0}\{1}", attachmentDirectoryName, DateTime.Now.ToString("yyyy-MM-dd").Replace('-', '\\')) + @"\Contract_" + serialNumber + @".pdf";

            //string strImagePath;

            //if (isPreview)
            //    strImagePath = @"\Images\watermark_preview.jpg";
            //else
            //    strImagePath = @"\Images\watermark_new.jpg";

            string htmlHead = @"PDF文档生成";
            string htmlTail = @"";

           

            PdfConverter pdfConverter = new PdfConverter();

            //pdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";

            //生成PDF文件相关格式设置
            pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
            pdfConverter.PdfDocumentOptions.TopMargin = 50;
            pdfConverter.PdfDocumentOptions.LeftMargin = 50;
            pdfConverter.PdfDocumentOptions.RightMargin = 50;
            pdfConverter.DrawBackground = false;
            pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
            pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
            pdfConverter.PdfStandardSubset = PdfStandardSubset.Full;
            pdfConverter.OptimizePdfPageBreaks = true;


            //PDF文件脚本、页眉、页脚及页码设置
            pdfConverter.PdfDocumentOptions.ShowFooter = true;
            pdfConverter.PdfDocumentOptions.InternalLinksEnabled = true;
            pdfConverter.ScriptsEnabled = false;
            pdfConverter.ScriptsEnabledInImage = false;
            pdfConverter.ScriptsEnabledInImage = false;

            pdfConverter.PdfFooterOptions.FooterHeight = 60;
            pdfConverter.PdfFooterOptions.FooterTextColor = Color.Black;
            pdfConverter.PdfFooterOptions.DrawFooterLine = false;
            pdfConverter.PdfFooterOptions.PageNumberTextFontName = "宋体";
            pdfConverter.PdfFooterOptions.ShowPageNumber = true;
            pdfConverter.PdfFooterOptions.PageNumberingFormatString = @"&p;                                                           ";
            pdfConverter.PdfFooterOptions.PageNumberingStartIndex = 9;
            pdfConverter.PdfFooterOptions.FooterTextFontName = "宋体";
            pdfConverter.PdfFooterOptions.PageNumberYLocation = 15.0f;

            //在服务器端生成PDF文档

            //Winnovative.WnvHtmlConvert.PdfDocument.Document document = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlHead +
            //    contractHTML + htmlTail, System.Web.HttpContext.Current.Server.MapPath("~" + strCSSPath));

            Winnovative.WnvHtmlConvert.PdfDocument.Document document = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlHead +
                contractHTML + htmlTail);
            document.TransparencyEnabled = true;

            //取得生成PDF文档对象的第一页,取得页面相关属性
            PdfPage firstPage = document.Pages[0];
            string logoImagePath = System.Web.HttpContext.Current.Server.MapPath("~" + strImagePath);
            ImageElement imageElement = new ImageElement(0, 0, logoImagePath);
            System.Drawing.Image logoImg = System.Drawing.Image.FromFile(logoImagePath);

            //计算用于水印的图片的坐标
            System.Drawing.SizeF imageSizePx = logoImg.PhysicalDimension;
            float imageWidth = UnitsConverter.PixelsToPoints(imageSizePx.Width);
            float imageHeight = UnitsConverter.PixelsToPoints(imageSizePx.Height);
            float templateWidth = firstPage.ClientRectangle.Width + 100;
            float templateHeight = firstPage.ClientRectangle.Height + 100;
            float w = firstPage.PageSize.Width / 4;
            float h = imageHeight / (imageWidth / w);

            //将图片加入到水印模板
            Template watermarkTemplate = document.AddTemplate(new System.Drawing.RectangleF(-60, -50, templateWidth, templateHeight));

            int m = (int)(templateWidth / w) + 1;
            int n = (int)(templateHeight / h) + 1;

            //将图片根据页面的尺寸复制
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    ImageElement watermarkImageElement = new ImageElement((w + 5.0F) * i, h * j, w, h, logoImg);
                    watermarkTemplate.AddElement(watermarkImageElement);
                }
            }

            watermarkTemplate.SendToBackground = true;

            try
            {
                if (!System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~" + strFileFolder)))
                    System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~" + strFileFolder));
                document.Save(System.Web.HttpContext.Current.Server.MapPath("~" + strFileName));
                document.Close();
                return strFileName;
            }
            catch (Exception)
            {
                //Logger.WriteLog("PDF文件生成错误", ex.ToString(), Capital.iWorkflow.Framework.Common.LogPriority.High, Capital.iWorkflow.Framework.Common.EventType.EVENT_ERROR);
                //AlertMessage("PDF文件生成错误!");
                return string.Empty;
            }
            finally
            {
                logoImg.Dispose();
            }
        }


    }
}

你可能感兴趣的:(HTML转PDF+水印以及PDF+水印)