Aspose.pdf使用教程
前言
1,选择多个文件(pdf或word)进行文档合并,并把文档的主要信息做成一个表格单页,文件中需要加入文字水印。
2,word转pdf可以看另一个帖子.net直接调用office com组件操作word转pdf
一、添加aspose.pdf使用类
代码如下(示例):
using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Aspose.Pdf.Facades;
using Aspose.Pdf;
using Aspose.Pdf.Text;
using Aspose.Pdf.Annotations;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
namespace Common
{
/// <summary>
/// Aspose pdf处理类
/// </summary>
public class AsposePdfClass
{
/// <summary>
/// //生成pdf表格文件
/// </summary>
/// <param name="outpdfPath">生成的表格的文件路径</param>
/// <param name="cellInfoArr">表格内容集合</param>
/// <param name="columnCount">表格内容的列数</param>
/// <returns></returns>
public string CreadPdfCell(string outpdfPath, JArray cellInfoArr, int columnCount)
{
try
{
先创建一个pdf
Document document = new Document();
// 添加一页
Page page = document.Pages.Add();
// Add text to new page
page.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment());
//保存 PDF
document.Save(outpdfPath);
//加载一个pdf
Aspose.Pdf.Document doc = new Aspose.Pdf.Document(outpdfPath);
// Initializes a new instance of the Table
Aspose.Pdf.Table table = new Aspose.Pdf.Table
{
ColumnAdjustment = ColumnAdjustment.AutoFitToWindow
};
//Aspose.Pdf.Table table = new Aspose.Pdf.Table();
//创建MarginInfo对象并设置其左,下,右和上边距
Aspose.Pdf.MarginInfo margin = new Aspose.Pdf.MarginInfo();
margin.Top = 5f;
margin.Left = 2f;
margin.Right = 2f;
margin.Bottom = 5f;
table.DefaultCellPadding = margin;
// Set the border for table cells
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
//设置表格字体样式
TextState cellTextState = new TextState();
cellTextState.ForegroundColor = Color.Black;//设置颜色
cellTextState.FontSize = 12F;//对应小四?
cellTextState.HorizontalAlignment = HorizontalAlignment.Center;//设置文字居中
cellTextState.Font = FontRepository.FindFont("SimSun"); //不设置字体会出现乱码现象
//cellTextState.FontStyle = FontStyles.Bold; //设置文字样式
foreach (JObject obj in cellInfoArr)
{
// Add row to table
Aspose.Pdf.Row row = table.Rows.Add();
foreach (var item in obj)
{
// Add table cells
row.Cells.Add(item.Value.ToString());
}
row.DefaultCellTextState = cellTextState;
}
// Add table object to first page of input document
doc.Pages[1].Paragraphs.Add(table);
// Save updated document containing table object
doc.Save(outpdfPath);
return "";
}
catch (Exception e)
{
return e.Message;
}
}
/// <summary>
/// 增加文字水印
/// </summary>
/// <param name="pdfPath">源文件路径</param>
/// <param name="title">文字水印内容</param>
/// <param name="title">输出的pdf路径</param>
public string AddWaterNote(string pdfPath, string title)
{
try
{
//open document
Document pdfDocument = new Document(pdfPath);
// Create text stamp
TextStamp textStamp = new TextStamp(title);
//设置是在pdf的内容上面还是下面
textStamp.Background = false;
//设置透明度 从0.0(完全透明)到1.0(完全不透明)
textStamp.Opacity = 0.3F;
// 设置x y坐标位置
//textStamp.XIndent = 280;
//textStamp.YIndent = 400;
//设置水平跟垂直的位置为居中
textStamp.HorizontalAlignment = HorizontalAlignment.Center;//设置文字居中
textStamp.VerticalAlignment = VerticalAlignment.Center;
// Rotate stamp
textStamp.Rotate = Rotation.None;
//设置字体必须用英文表示!!! 宋体这里要用英文标示SimSun,中文不识别
textStamp.TextState.Font = FontRepository.FindFont("SimSun");//ArialTimesNewRoman
//字体大小
textStamp.TextState.FontSize = 100F;
textStamp.TextState.FontStyle = FontStyles.Bold;
textStamp.TextState.FontStyle = FontStyles.Regular;
textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray);
//给每一个都加上文字水印
int size = pdfDocument.Pages.Count();
//这里下标从1 开始,切记(试用版本仅支持前四页的水印内容)
if (size > 4)
{
size = 4;
}
for (int i = 1; i <= size; i++)
{
pdfDocument.Pages[i].AddStamp(textStamp);
}
pdfDocument.Save(pdfPath);
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// pdf合并
/// </summary>
/// <param name="outPath">合并后的文件输出地址</param>
/// <param name="printDic">需要打印的文件集合</param>
/// <returns></returns>
public string PdfMerge(string outPath, Dictionary<int, string> printDic)
{
PdfFileEditor pdfEditor = new PdfFileEditor();
int fileCount = printDic.Count;
FileStream[] streamArray = new FileStream[fileCount];
FileStream outputStream = new FileStream(outPath, FileMode.Create);
int arrIndex = 0;
foreach (var item in printDic)
{
streamArray[arrIndex] = new FileStream(item.Value, FileMode.Open);
arrIndex = arrIndex + 1;
}
try
{
pdfEditor.Concatenate(streamArray, outputStream);
outputStream.Close();
foreach (FileStream fs in streamArray)
{
fs.Close();
}
return "";
}
catch (Exception e)
{
return e.Message;
}
}
}
}
二、如何使用
文件转换比较耗时,所以方法写成了异步处理的,
代码如下(示例):
public IActionResult batchPrint()
{
try
{
string msg = string.Empty;
Dictionary<string, string> requestParams = GetRequestParameters();
string docName = requestParams["docNewNm"];
List<dynamic> selDataIds = JsonConvert.DeserializeObject<List<dynamic>>(requestParams["docArr"]);
Dictionary<int, int> rstDic = new Dictionary<int, int>();
DataTable docDT = new DataTable();
docDT.Columns.Add("docId");//文件Id
docDT.Columns.Add("printSort");//打印顺序
docDT.Columns.Add("printPath");//文件地址
docDT.Columns.Add("fileNm");//文件名称
docDT.Columns.Add("fileNo");//文件编号
docDT.Columns.Add("edition");//版本号
docDT.Columns.Add("revise");//修订号
docDT.Columns.Add("isrtDt");//修改日期
//取最后一个文件的存放地址作为本次操作的文件地址
string opPath = string.Empty;
foreach (var item in selDataIds)
{
//获取对应的文件id
int quoteFileId = Convert.ToInt32(item["quoteFileId"]);
int fileId = Convert.ToInt32(item["id"]);
var model = commonService.GetModel<DV_File>(t => t.fileId == quoteFileId);
opPath = model.absolutPath;
//要打印的文件的物理路径
string printPath = model.absolutPath + model.preFileNm;
//获取文档信息
vAP_DS_Document vDoc = commonService.GetModel<vAP_DS_Document>(t => t.id == fileId);
string docNo = vDoc.documentTypeNm + "-" + vDoc.firstDocumentGroupNm + "-" + vDoc.edition + "-" + vDoc.documentIndex + "-" + vDoc.revise;
//保存文件信息
docDT.Rows.Add(new object[] { fileId, item["printSort"], printPath, model.preFileNm, docNo, vDoc.edition, vDoc.revise, vDoc.isrtDt });
}
docDT.DefaultView.Sort = "printSort asc";//按打印号顺序排序
docDT = docDT.DefaultView.ToTable();//返回一个新的DataTable
DocumentOperate(docName, opPath, docDT, CurrentUser, commonService);
return OC.Cur.GenJson();
}
catch (Exception ex)
{
return OC.Cur.GenJson(null, false, ex.Message);
}
}
/// <summary>
/// 文档处理
/// </summary>
/// <param name="opPath">文件存放目录</param>
/// <param name="docDT">key:文档信息集合</param>
/// <returns></returns>
public async void DocumentOperate(string docName, string opPath, DataTable docDT, vDV_Eemployee CurrentUser, ICommonService commonService2)
{
await Task.Run(() =>
{
AP_DS_DocumentPrintList pModel = new AP_DS_DocumentPrintList();
pModel.departId = CurrentUser.departId;
pModel.isrtUserId = CurrentUser.empId;
pModel.isrtUserName = CurrentUser.empNm;
pModel.docName = docName;
try
{
string msg = "";
WordClass wc = new WordClass();
AsposePdfClass pdf = new AsposePdfClass();
//需要打印的pdf集合
Dictionary<int, string> printDic = new Dictionary<int, string>();
#region //生成第一个pdfde 表格信息
string cellPdfNm = Guid.NewGuid().ToString() + ".pdf";//取一个随机名
#region//表头数据做成
JArray cellArr = new JArray();
JObject headercell = new JObject();
headercell.Add("v1", "文件编号");
headercell.Add("v2", "版本号");
headercell.Add("v3", "修订号");
headercell.Add("v4", "修改日期");
headercell.Add("v5", "序号");
cellArr.Add(headercell);
#endregion
//生成一个输出pdf的路径
string outpdfPath = opPath + "cell" + cellPdfNm;
int dicKey = 1;
printDic.Add(dicKey, outpdfPath);//将表格数据作为第一个要打印的文本
#endregion
List<string> idList = new List<string>();
//遍历需要打印的文档集合
foreach (DataRow dr in docDT.Rows)
{
idList.Add(dr["docId"].ToString());
//获取文件路径
string curPath = dr["printPath"].ToString();
//获取文件类型名
string fileType = System.IO.Path.GetExtension(curPath);//扩展名 “.aspx”
string fileName = System.IO.Path.GetFileNameWithoutExtension(curPath);// 没有扩展名的文件名 “Default”
string pdfPath = "";
//只有word才需要转成pdf
if (fileType.Contains(".doc"))
{
pdfPath = opPath + fileName + ".pdf";//生成一个pdf的路径
msg = wc.WordToPDF(curPath, pdfPath);//将word转成pdf
if (!string.IsNullOrEmpty(msg))
{
//添加记录及出错原因
pModel.note = "[" + fileName + fileType + "]转pdf时异常:" + msg;
pModel.isSuccess = false;
pModel.isrtDt = DateTime.Now;
newSql.AddDocPrintList(pModel);
return OC.Cur.GenJson(null, false, msg);
}
}
else
{
pdfPath = curPath;//如果是pdf文件,则直接复制
}
//将pdf文件加入水印
msg = pdf.AddWaterNote(pdfPath, dr["printSort"].ToString());
if (!string.IsNullOrEmpty(msg))
{
//添加记录及出错原因
pModel.note = "[" + fileName + ".pdf]增加水印时异常:" + msg;
pModel.isrtDt = DateTime.Now;
pModel.isSuccess = false;
newSql.AddDocPrintList(pModel);
return OC.Cur.GenJson(null, false, msg);
}
//生成第一页pdf表格中的数据内容
JObject detailcell = new JObject();
detailcell.Add("v1", dr["fileNo"].ToString());//文件编号
detailcell.Add("v2", dr["edition"].ToString());//版本号
detailcell.Add("v3", dr["revise"].ToString());//修订号
detailcell.Add("v4", dr["isrtDt"].ToString());//修改日期
detailcell.Add("v5", dr["printSort"].ToString());//打印序号
cellArr.Add(detailcell);
dicKey = dicKey + 1;
printDic.Add(dicKey, pdfPath);
}
//生成pdf表格
msg = pdf.CreadPdfCell(outpdfPath, cellArr, 5);
if (!string.IsNullOrEmpty(msg))
{
//添加记录及出错原因
pModel.note = "生成pdf表格时异常:" + msg;
pModel.isrtDt = DateTime.Now;
pModel.isSuccess = false;
newSql.AddDocPrintList(pModel);
return OC.Cur.GenJson(null, false, msg);
}
string mergePath = opPath + "merge" + cellPdfNm;
//合并所有的文档到一个pdf
msg = pdf.PdfMerge(mergePath, printDic);
if (!string.IsNullOrEmpty(msg))
{
//添加记录及出错原因
pModel.note = "合并所有的pdf时异常:" + msg;
pModel.isrtDt = DateTime.Now;
pModel.isSuccess = false;
newSql.AddDocPrintList(pModel);
return OC.Cur.GenJson(null, false, msg);
}
//添加记录及出错原因
pModel.note = "合并成功";
pModel.isrtDt = DateTime.Now;
pModel.filePath = mergePath;
string ttt = string.Join(",", idList.ToArray());
pModel.docIds = string.Join(",", idList.ToArray());
pModel.isSuccess = true;
newSql.AddDocPrintList(pModel);
return OC.Cur.GenJson();
}
catch (Exception ex)
{
//添加记录及出错原因
pModel.note = "catch异常:" + ex.Message;
pModel.isrtDt = DateTime.Now;
pModel.isSuccess = false;
newSql.AddDocPrintList(pModel);
return OC.Cur.GenJson(null, false, ex.Message);
}
});
}
总结
记录项目过程中对aspose.pdf的使用。