將數據寫入Word模版,生成PDF並加水印


需要引用,DLL請自行下載

using Aspose.Pdf;
using Aspose.Words;
using System.Data;
using System.IO;

首選創建Word數據模版;使用Office或者WPS創建一個DOC模版,並增加域;如何增加域名可自行搜索

WPS增加 使郵件合並

 

然后制做出以下類似模版

 

 

關於輸出列表;需要使用 域 

 

將你要循環輸出的字段包住

 

 

//這里獲取Table數據源,表的列名需要與模版中的域名對應
            DataTable dt = new DataTable();
            //這里獲取列表數據的數據源;表的列名也需要與域名對應
            DataTable dtlist = new DataTable();

            //建議列表數據列最好不要與單一數據的表存在相同的列名稱
            string _templatePath = "template.doc"; //模板路徑
            _templatePath = Server.MapPath(_templatePath);
            string _savePath = "/out/"; //保存生成文檔路徑
            string sp = Server.MapPath(_savePath);
            string f = Guid.NewGuid().ToString("N") + ".doc";
            string copyto = sp + f;

            File.Copy(_templatePath.ToString(), copyto, true); //將文件復制到結果文檔中
            Aspose.Words.Document doc = new Aspose.Words.Document(copyto);
            Aspose.Words.DocumentBuilder builder = new DocumentBuilder(doc);
            //先進行列表數據的替換,注意DataTable.TableName屬性要與 «TableStart:s2198» 域名保持一致
            doc.MailMerge.ExecuteWithRegions(dtlist);


            foreach (DataRow r in dt.Rows)
            {
                //這里獲取列名,請注意更改為自己獲取列名的邏輯
                string field = string.Format("s{0}", r["itemid"].ToString());//
                while (builder.MoveToMergeField(field))
                {
                    builder.Write(r["value"].ToString());//寫入值
                }
            }

            //到此,往WORD模版里寫入數據的邏輯就已經完成,接下來將數據保存為PDF

            MemoryStream docStream = new MemoryStream();
            doc.Save(docStream, Aspose.Words.SaveFormat.Pdf);
            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(docStream);
            //增加水印圖片,將圖片放在根目錄下
            ImageStamp imageStamp = new ImageStamp(Server.MapPath("waterMark3_3.gif"));
            imageStamp.Background = true;
            //設置了圖片寬高;不設置則按照實際圖片寬高
            //imageStamp.Height = 350;
            //imageStamp.Width = 350;
            imageStamp.Opacity = 0.5;
            //水印位置
            imageStamp.HorizontalAlignment = HorizontalAlignment.Center;
            imageStamp.VerticalAlignment = VerticalAlignment.Center;
            //為PDF的每個頁面都加上水印
            for (int j = 1; j <= pdfDocument.Pages.Count; j++)
            {
                pdfDocument.Pages[j].AddStamp(imageStamp);
            }
            //保存PDF
            pdfDocument.Save(docStream);
            //如果是頁面的話,可以下載PDF
            Response.ContentType = "application/msword";
            Response.AddHeader("content-disposition", "attachment;  filename=Print" + child.Rows.Count + ".pdf");
            Response.BinaryWrite(docStream.ToArray());
            Response.End();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM