您的位置:首页 > 编程语言 > C#

C#生成word文档 、word转pdf、合并pdf文件等

2018-03-17 17:33 921 查看

C#生成word文档 、word转pdf、合并pdf文件等

在系统开发中经常会有用户需求涉及到基于模板导出word文档、pdf文档,或者把几个文件合并成一个进行导出预览等,他们所说需求不一样,但在功能实现上却是相同的。由于前期在使用时对pdf涉及的不太多,所以在文件导出时都是用的word转pdf形式。

备注:在当前文章中所涉及到的模板均为.doc文件。

需求描述

用户根据表单填写基本信息,需要单个或者批量导出信息到word文档中。

模板准备:

1.空模板.doc //作为合并文件时的模板使用

2.表单模板.doc //导出word模板

代码如下:

using Aspose.Words;
using iTextSharp.text.pdf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;

public string HelloWorld()
{
var result = new { statue = "fail", url = "" };
try
{
Student bll = new Student();
string tempPath = HttpContext.Current.Server.MapPath("~/");//系统部署地址

#region 创建文件夹

List<string> li = new List<string>();
List<Student> list = GetStudentData();
foreach (Student model in list)
{
Document doc = new Document(tempPath + "表单模板.doc");//加载模板
string fName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + model.name + ".doc";
string savePath = tempPath + fName;//文件保存路径
//根据word中的标签赋值
doc.Range.Bookmarks["NAME"].Text = "张三";
doc.Range.Bookmarks["SEX"].Text = "男";
doc.Range.Bookmarks["AGE"].Text = "18";

doc.Save(savePath, SaveFormat.Doc);
DOCConvertToPDF(savePath, savePath.Replace(".doc", ".pdf"));
li.Add(savePath.Replace(".doc", ".pdf"));//生成附件的list集合
}
#endregion 创建文件夹
//保存文件路径
string sPath = tempPath + "_导出基本信息.doc";
string pdf_path = sPath.Replace(".doc", ".pdf");
DOCConvertToPDF(tempPath + "空模板.doc", pdf_path);
MergePDFFiles(li.ToArray(), pdf_path);//合并文件

//删除转换后的文件
foreach (PdfModel model in mergeFile_temp)
{
model.pdf.Dispose();
File.Delete(model.url);//删除临时文件
File.Delete(model.url.Replace(".pdf", ".word"));
}

result = new { statue = "success", url = pdf_path };
}
catch (Exception ex)
{
}
return JsonConvert.SerializeObject(result); ;
}

/// <summary> 合并PDF </summary>
/// <param name="fileList">PDF文件集合</param>
/// <param name="outMergeFile">合并文件名</param>
///
public static void MergePDFFiles(string[] fileList, string outMergeFile)
{
PdfReader reader;
iTextSharp.text.Rectangle re;
PdfDictionary pd;
//List<PdfReader> readerList = new List<PdfReader>();//记录合并PDF集合
iTextSharp.text.Document document = new iTextSharp.text.Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
document.Open();

PdfContentByte cb = writer.DirectContent;
PdfImportedPage newPage;
for (int i = 0; i < fileList.Length; i++)
{
if (!string.IsNullOrEmpty(fileList[i]))
{
reader = new PdfReader(fileList[i]);
PdfModel model = new PdfModel();
model.pdf = reader;
model.url = fileList[i];
mergeFile_temp.Add(model);

int iPageNum = reader.NumberOfPages;
for (int j = 1; j <= iPageNum; j++)
{
//获取Reader的pdf页的打印方向
re = reader.GetPageSize(reader.GetPageN(j));
//设置合并pdf的打印方向
document.SetPageSize(re);
document.NewPage();
newPage = writer.GetImportedPage(reader, j);
cb.AddTemplate(newPage, 0, 0);
}
//reader.Dispose();
//readerList.Add(reader);
}
}
document.Close();
//Process.Start(outMergeFile);//预览
}

private static bool DOCConvertToPDF(string sourcePath, string targetPath)
{
bool result;
try
{
Aspose.Words.Document document = new Aspose.Words.Document(sourcePath);
document.Save(targetPath, Aspose.Words.SaveFormat.Pdf);
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}

public static List<Student> GetStudentData()
{

List<Student> list = new List<Student>();

for (int index = 0; index < 3; index++)
{
Student model = new Student();
model.name = "张三_" + index;
model.sex = "男-" + index;
model.age = index.ToString();
list.Add(model);
}
return list;
}
//访问实体类
public class Student
{
/// <summary>
/// 姓名
/// </summary>
public string name
{
set;
get;
}
/// <summary>
/// 性别
/// </summary>
public string sex
{
set;
get;
}
/// <summary>
/// 年龄
/// </summary>
public string age
{
set;
get;
}

}
public class PdfModel
{
public PdfReader pdf
{
set;
get;
}
public string url
{
set;
get;
}
}

... prompt'''


文章中所涉及的模板为:



生成的文件格式为:



关于引用文件暂时无法上传。

关于合并文件的暂时没有找到好的方法,都先凑合着用吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息