winform 替换word文档中的字段(包含图片添加),生成导出PDF文件(也可是word文件)

时间:2023-03-10 02:04:15
winform  替换word文档中的字段(包含图片添加),生成导出PDF文件(也可是word文件)

1.先打开你需要替换的word文档,在想要后续更换字段值的地方添加“书签”。

winform  替换word文档中的字段(包含图片添加),生成导出PDF文件(也可是word文件)

2.将模板文档存放在 程序的Debug文件下。

3.生成文件的按钮点击事件 代码:

   string templatePath = Application.StartupPath + "\\模板.docx"; //文档模板物理路径

                Document doc = new Document(templatePath);
try
{
Hashtable tables = new Hashtable();
tables.Add("A型", aJ);
tables.Add("A价", aF);
tables.Add("B型", bJ);
tables.Add("B价", bF);
tables.Add("F型", fJ);
tables.Add("F价", fF); //图片添加
//Aspose.Words.DocumentBuilder builder1 = new Aspose.Words.DocumentBuilder(doc);
//// Response.ContentType = pictureBox1.ImageLocation;//设定输出文件类型
//builder1.MoveToBookmark("图片审核者");
//builder1.InsertImage((byte[])GetPictureData(pictureBox1.ImageLocation), 60, 30); tables.Add("日期", dtpBaogao.Value.ToString("yyyy年MM月dd日"));
tables.Add("日期2", dtpJieshou.Value.ToString("yyyy.MM.dd"));
GetHTFile(doc, tables); string downname = txtName.Text + "----报告.pdf";
// doc.Save(downname, SaveFormat.Pdf); SaveFileDialog SaveData = new SaveFileDialog(); //以保存文件的方式打开
SaveData.RestoreDirectory = true; //显示上次存放的目录
SaveData.Title = "请选择路径"; //标题
//SaveData.InitialDirectory = @"C:\"; //默认路径是C:\,可更改
SaveData.Filter = "PDF文件(*.pdf)|*.pdf"; //只能保存为sql文件(可根据需求更改) string script = " "; SaveData.FileName = txtName.Text + "----报告";
if (SaveData.ShowDialog() == DialogResult.OK) //如果选定路径按下保存按钮
{
script = SaveData.FileName; //script赋值为选择保存的路径
doc.Save(script, SaveFormat.Pdf); //生成word文件,就将 SaveFormat.Pdf改成.word
MessageBox.Show("生成成功!"); this.Close();
}
}
catch (Exception ex)
{ } }
public byte[] GetPictureData(string imagepath)
{
/**/////根据图片文件的路径使用文件流打开,并保存为byte[]
FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法
byte[] byData = new byte[fs.Length];
fs.Read(byData, , byData.Length);
fs.Close();
return byData;
}
public static void GetHTFile(Document doc, Hashtable table)
{
BookmarkCollection bookmarks = doc.Range.Bookmarks;
foreach (Bookmark mark in bookmarks)
{
if (table.ContainsKey(mark.Name))
{
mark.Text = table[mark.Name].ToString();
}
}
}

注:需要引用 Aspose.Words.dll