C#&.Net干货分享- 构建Spire-Office相关Helper操作Word、Excel、PDF等
先下载好如下的组件:
直接使用完整源码分享:
namespace Frame.Office
{
/// <summary>
/// Spire_WordHelper
/// </summary>
public static class Spire_WordHelper
{
/// <summary>
/// 设置Word图片水印
/// </summary>
/// <param name="wordFilepath"></param>
/// <param name="imageFilepath"></param>
/// <param name="waterMarkSavePath"></param>
public static void SetWordImageWaterMark(string wordFilepath, string imageFilepath, string waterMarkSavePath)
{
Document doc = new Document();
doc.LoadFromFile(wordFilepath);
PictureWatermark picture = new PictureWatermark();
picture.Picture = Image.FromFile(imageFilepath);
picture.Scaling = 80;
doc.Watermark = picture;
doc.SaveToFile(waterMarkSavePath);
}
/// <summary>
///
/// </summary>
/// <param name="wordFilepath"></param>
/// <param name="waterMarkText"></param>
/// <param name="fontSize"></param>
/// <param name="waterMarkSavePath"></param>
public static void SetWordTextWaterMark(string wordFilepath, string waterMarkText, float fontSize, string waterMarkSavePath)
{
Document document = new Document();
document.LoadFromFile(wordFilepath);
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = waterMarkText;
txtWatermark.FontSize = fontSize;
txtWatermark.Layout = WatermarkLayout.Diagonal;
document.Watermark = txtWatermark;
document.SaveToFile(waterMarkSavePath);
}
/// <summary>
/// 读取源文档表头文档的标题并将其仅插入另一个文档的第一页
/// </summary>
/// <param name="sourceWordFilepath">源文档路径</param>
/// <param name="toWordFilepath">目标文档路径</param>
/// <param name="saveWordFilepath">加工后保存的文档路径</param>
public static void SetDocumentHeaderFooter(string sourceWordFilepath, string toWordFilepath, string saveWordFilepath)
{
Document sourceDocument = new Document();
sourceDocument.LoadFromFile(sourceWordFilepath);
Document toDocument = new Document();
toDocument.LoadFromFile(toWordFilepath);
HeaderFooter sourceHeaderFooter = sourceDocument.Sections[0].HeadersFooters.Header;
HeaderFooter firstPageHeader = toDocument.Sections[0].HeadersFooters.FirstPageHeader;
foreach (Section section in toDocument.Sections)
{
section.PageSetup.DifferentFirstPageHeaderFooter = true;
}
firstPageHeader.Paragraphs.Clear();
foreach (DocumentObject documentObject in sourceHeaderFooter.ChildObjects)
{
firstPageHeader.ChildObjects.Add(documentObject.Clone());
}
toDocument.SaveToFile(saveWordFilepath, Spire.Doc.FileFormat.Docx);
}
/// <summary>
/// 设置文档某一个段落的背景色
/// </summary>
/// <param name="sourceWordFilepath"></param>
/// <param name="saveWordFilepath"></param>
/// <param name="paragraphsIndex"></param>
/// <param name="colorType"></param>
public static void SetDocumentParagraphBackColor(string sourceWordFilepath, string saveWordFilepath, int paragraphsIndex, Color colorType)
{
Document sourceDocument = new Document();
sourceDocument.LoadFromFile(sourceWordFilepath);
Paragraph paragaph = sourceDocument.Sections[0].Paragraphs[paragraphsIndex];
paragaph.Format.BackColor = colorType;
sourceDocument.SaveToFile(saveWordFilepath, Spire.Doc.FileFormat.Docx);
}
/// <summary>
/// 设置文档内某个指定文本,所有位置的都是高亮文本
/// </summary>
/// <param name="sourceWordFilepath"></param>
/// <param name="saveWordFilepath"></param>
/// <param name="paragraphsIndex"></param>
/// <param name="highlightText"></param>
/// <param name="colorType"></param>
public static void SetDocumentAllParagraphTextBackgroundColor(string sourceWordFilepath, string saveWordFilepath, string highlightText, Color colorType)
{
Document sourceDocument = new Document();
sourceDocument.LoadFromFile(sourceWordFilepath);
int paragraphsCount = sourceDocument.Sections[0].Paragraphs.Count;
Paragraph paragaph = null;
TextSelection textSelection = null;
TextRange textRange = null;
for (int ii = 0; ii < paragraphsCount - 1; ii++)
{
paragaph = sourceDocument.Sections[0].Paragraphs[ii];
textSelection = paragaph.Find(highlightText, true, false);
textRange = textSelection.GetAsOneRange();
textRange.CharacterFormat.TextBackgroundColor = colorType;
}
sourceDocument.SaveToFile(saveWordFilepath, Spire.Doc.FileFormat.Docx);
}
/// <summary>
/// 设置文档某一个段落内某个文本为高亮文本
/// </summary>
/// <param name="sourceWordFilepath"></param>
/// <param name="saveWordFilepath"></param>
/// <param name="paragraphsIndex"></param>
/// <param name="highlightText"></param>
/// <param name="colorType"></param>
public static void SetDocumentParagraphTextBackgroundColor(string sourceWordFilepath, string saveWordFilepath, int paragraphsIndex, string highlightText, Color colorType)
{
Document sourceDocument = new Document();
sourceDocument.LoadFromFile(sourceWordFilepath);
Paragraph paragaph = sourceDocument.Sections[0].Paragraphs[paragraphsIndex];
TextSelection textSelection = paragaph.Find(highlightText, true, false);
TextRange textRange = textSelection.GetAsOneRange();
textRange.CharacterFormat.TextBackgroundColor = colorType;
sourceDocument.SaveToFile(saveWordFilepath, Spire.Doc.FileFormat.Docx);
}
/// <summary>
/// 删除文档的页与页之间的分页符号
/// </summary>
/// <param name="sourceWordFilepath"></param>
/// <param name="fileFormat"></param>
/// <param name="saveWordFilepath"></param>
public static void DeleteDocumentObjectBreak(string sourceWordFilepath, Spire.Doc.FileFormat fileFormat, string saveWordFilepath)
{
Document sourceDocument = new Document();
sourceDocument.LoadFromFile(sourceWordFilepath, fileFormat);
for (int ii = 0; ii < sourceDocument.Sections[0].Paragraphs.Count; ii++)
{
Paragraph paragraph = sourceDocument.Sections[0].Paragraphs[ii];
for (int jj = 0; jj < paragraph.ChildObjects.Count; jj++)
{
DocumentObject documentObject = paragraph.ChildObjects[jj];
if (documentObject.DocumentObjectType == DocumentObjectType.Break)
{
Break bBreak = documentObject as Break;
paragraph.ChildObjects.Remove(bBreak);
}
}
}
sourceDocument.SaveToFile(saveWordFilepath, fileFormat);
}
/// <summary>
///
/// </summary>
/// <param name="sourceFilePath"></param>
/// <param name="errMsg"></param>
/// <returns></returns>
public static bool DocumentToPdf(string sourcePathFileName, string targetPathFileName)
{
bool flag = true;
try
{
Regex regexExcel = new Regex(@"^.*?\.(xls|xlsx)$");
Regex regexWord = new Regex(@"^.*?\.(doc|docx|ppt|pptx)$");
string fileName = Path.GetFileName(sourcePathFileName).ToLower();
if (regexExcel.IsMatch(fileName))//Excel
{
Workbook workbook = new Workbook();
workbook.LoadFromFile(sourcePathFileName);
workbook.SaveToFile(targetPathFileName, Spire.Xls.FileFormat.PDF);
}
else if (regexWord.IsMatch(fileName))//Word
{
Document document = new Document(sourcePathFileName);
document.SaveToFile(targetPathFileName, Spire.Doc.FileFormat.PDF);
}
}
catch
{
flag = false;
}
return flag;
}
}
/// <summary>
/// Spire_PDFHelper导出数据源到PDF
/// </summary>
public static class Spire_PDFHelper
{
/// <summary>
/// 提取PDF文件的文本内容
/// </summary>
/// <param name="pdfFilepath"></param>
/// <returns></returns>
public static string ReadPdfText(string pdfFilepath)
{
try
{
PdfDocument docPdf = new PdfDocument();
docPdf.LoadFromFile(pdfFilepath);
StringBuilder buffer = new StringBuilder();
foreach (PdfPageBase page in docPdf.Pages)
{
if (page.ExtractImages() != null)
{
List<Bitmap> bitmaps = new List<Bitmap>();
foreach (Image image in page.ExtractImages())
{
Bitmap bitmap = new Bitmap(image);
bitmaps.Add(bitmap);
}
buffer.Append(Aocr_ImageHelper.ReadBitmapText(bitmaps, AspriseOCRLanguages.LANGUAGE_ENG));
}
buffer.Append(page.ExtractText());
}
docPdf.Close();
return buffer.ToString();
}
catch
{
return string.Empty;
}
}
/// <summary>
/// 提取PDF中的图片
/// </summary>
/// <param name="pdfFilepath"></param>
public static void ReadPdfImage(string pdfFilepath)
{
try
{
PdfDocument docPdf = new PdfDocument();
docPdf.LoadFromFile(pdfFilepath);
IList<Image> images = new List<Image>();
foreach (PdfPageBase page in docPdf.Pages)
{
if (page.ExtractImages() != null)
{
foreach (Image image in page.ExtractImages())
{
images.Add(image);
}
}
}
docPdf.Close();
int index = 0;
foreach (Image image in images)
{
String imageFileName = String.Format("Image-{0}.png", index++);
image.Save(imageFileName, ImageFormat.Png);
}
}
catch
{
}
}
/// <summary>
/// PDF增加图片水印
/// </summary>
/// <param name="pdfFilepath">源PDF文件</param>
/// <param name="imageFilepath">水印图片</param>
/// <param name="waterMarkSavePath">水印文件保存路径</param>
public static void SetPdfImageWaterMark(string pdfFilepath, string imageFilepath, string waterMarkSavePath)
{
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(pdfFilepath);
Image image = Image.FromFile(imageFilepath);
foreach (PdfPageBase pdfPageBase in pdf.Pages)
{
pdfPageBase.BackgroundImage = image;
}
pdf.SaveToFile(waterMarkSavePath);
}
/// <summary>
/// PDF增加文本水印
/// </summary>
/// <param name="pdfFilepath">源PDF文件</param>
/// <param name="spireTextWaterMarkPara">水印参数</param>
/// <param name="waterMarkSavePath">水印文件保存路径</param>
public static void SetPdfTextWaterMark(string pdfFilepath, SpireTextWaterMarkPara spireTextWaterMarkPara, string waterMarkSavePath)
{
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(pdfFilepath);
foreach (PdfPageBase pdfPageBase in pdf.Pages)
{
SizeF sizeF = new SizeF(spireTextWaterMarkPara.Width, spireTextWaterMarkPara.Height);
PdfTilingBrush brush = new PdfTilingBrush(sizeF);
brush.Graphics.SetTransparency(spireTextWaterMarkPara.Alpha);
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
brush.Graphics.RotateTransform(spireTextWaterMarkPara.RotateDegree);
PdfFont pdfFont = new PdfFont(spireTextWaterMarkPara.PdfFontFamily, spireTextWaterMarkPara.FontSize);
PdfStringFormat pdfStringFormat = new PdfStringFormat(spireTextWaterMarkPara.PdfTextAlignment);
brush.Graphics.DrawString(spireTextWaterMarkPara.WaterMarkText, pdfFont, spireTextWaterMarkPara.PdfBrush, spireTextWaterMarkPara.XCoordinate, spireTextWaterMarkPara.YCoordinate, pdfStringFormat);
brush.Graphics.Restore();
brush.Graphics.SetTransparency(spireTextWaterMarkPara.Alpha);
RectangleF rectangleF = new RectangleF(new PointF(0, 0), pdfPageBase.Canvas.ClientSize);
pdfPageBase.Canvas.DrawRectangle(brush, rectangleF);
}
pdf.SaveToFile(waterMarkSavePath);
}
/// <summary>
///
/// </summary>
public static void SetPdfDocumentSignature(DataTable dataTable, PdfSignatureInfo pdfSignatureInfo, string saveWordFilepath)
{
PdfDocument pdfDocument = new PdfDocument();
PdfPageBase pdfPageBase = pdfDocument.Pages.Add(PdfPageSize.A4);
float y = 10;
PdfTable pdfTable = new PdfTable();
pdfTable.Style.CellPadding = 2;
PdfBrush pdfBrush = PdfBrushes.Black;
pdfTable.Style.BorderPen = new PdfPen(pdfBrush, 0.75f);
pdfTable.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue;
pdfTable.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f));
pdfTable.Style.AlternateStyle = new PdfCellStyle();
pdfTable.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow;
pdfTable.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f));
pdfTable.Style.HeaderSource = PdfHeaderSource.ColumnCaptions;
pdfTable.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
pdfTable.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
pdfTable.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
pdfTable.Style.ShowHeader = true;
pdfTable.DataSourceType = PdfTableDataSourceType.TableDirect;
pdfTable.DataSource = dataTable;
float width = pdfPageBase.Canvas.ClientSize.Width - (pdfTable.Columns.Count + 1) * pdfTable.Style.BorderPen.Width;
pdfTable.Columns[0].Width = width * 0.24f * width;
pdfTable.Columns[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
pdfTable.Columns[1].Width = width * 0.21f * width;
pdfTable.Columns[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
pdfTable.Columns[2].Width = width * 0.24f * width;
pdfTable.Columns[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
pdfTable.Columns[3].Width = width * 0.13f * width;
pdfTable.Columns[3].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
pdfTable.Columns[4].Width = width * 0.18f * width;
pdfTable.Columns[4].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
PdfLayoutResult result = pdfTable.Draw(pdfPageBase, new PointF(30, y));
y = y + result.Bounds.Height + 10;
PdfCertificate pdfCertificate = new PdfCertificate(pdfSignatureInfo.PdfCertificatePath, pdfSignatureInfo.PdfCertificatePathPwd);
PdfSignature pdfSignature = new PdfSignature(pdfDocument, pdfPageBase, pdfCertificate, pdfSignatureInfo.PdfSignatureName);
RectangleF rectangleF = new RectangleF(new PointF(150, y), new SizeF(260, 90));
pdfSignature.Bounds = rectangleF;
SetPdfSignatureInfo(pdfSignature, pdfSignatureInfo);
pdfDocument.SaveToFile(saveWordFilepath, Spire.Pdf.FileFormat.PDF);
}
/// <summary>
/// 设置签章属性
/// </summary>
/// <param name="pdfSignature"></param>
/// <param name="pdfSignatureInfo"></param>
public static void SetPdfSignatureInfo(PdfSignature pdfSignature, PdfSignatureInfo pdfSignatureInfo)
{
pdfSignature.NameLabel = pdfSignatureInfo.NameLabel;
pdfSignature.Name = pdfSignatureInfo.Name;
pdfSignature.DistinguishedName = pdfSignatureInfo.DistinguishedName;
pdfSignature.LocationInfoLabel = pdfSignatureInfo.LocationInfoLabel;
pdfSignature.LocationInfo = pdfSignatureInfo.LocationInfo;
pdfSignature.ReasonLabel = pdfSignatureInfo.ReasonLabel;
pdfSignature.Reason = pdfSignatureInfo.Reason;
pdfSignature.DateLabel = pdfSignatureInfo.DateLabel;
pdfSignature.Date = pdfSignatureInfo.Date;
pdfSignature.ContactInfoLabel = pdfSignatureInfo.ContactInfoLabel;
pdfSignature.ContactInfo = pdfSignatureInfo.ContactInfo;
pdfSignature.Certificated = pdfSignatureInfo.Certificated;
pdfSignature.GraphicsMode = pdfSignatureInfo.GraphicsMode;
pdfSignature.SignImageSource = PdfImage.FromFile(pdfSignatureInfo.SignImageSourcePath);
pdfSignature.DocumentPermissions = PdfCertificationFlags.ForbidChanges;
}
}
/// <summary>
/// Spire操作excel
/// </summary>
public static class Spire_ExcelHelper
{
/// <summary>
/// Excel增加水印
/// </summary>
/// <param name="fileName"></param>
/// <param name="watermarkText"></param>
/// <returns></returns>
public static string AddExcelSpire(string fileName, string watermarkText)
{
//初始化一个新工作簿并加载要添加水印的文件
Workbook workbook = new Workbook();
workbook.LoadFromFile(fileName);
//在页眉插入图片
Font font = new Font("arial", 40);
foreach (Worksheet sheet in workbook.Worksheets)
{
//调用DrawText()方法新建图片
Image imgWtrmrk = DrawText(watermarkText, font, Color.LightCoral, System.Drawing.Color.White, sheet.PageSetup.PageHeight, sheet.PageSetup.PageWidth);
////将页眉图片设置为左对齐
//sheet.PageSetup.LeftHeaderImage = imgWtrmrk;
//sheet.PageSetup.LeftHeader = "&G";
////水印只会在此种模式下显现
//sheet.ViewMode = ViewMode.Layout;
sheet.PageSetup.BackgoundImage = imgWtrmrk as Bitmap;
}
workbook.SaveToFile(fileName);
return string.Empty;
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <param name="font"></param>
/// <param name="textColor"></param>
/// <param name="backColor"></param>
/// <param name="height"></param>
/// <param name="width"></param>
/// <returns></returns>
private static Image DrawText(String text, System.Drawing.Font font, Color textColor, Color backColor, double height, double width)
{
//创建一个指定宽度和高度的位图图像
Image img = new Bitmap((int)width, (int)height);
Graphics drawing = Graphics.FromImage(img);
//获取文本大小
SizeF textSize = drawing.MeasureString(text, font);
//旋转图片
drawing.TranslateTransform(((int)width - textSize.Width) / 2, ((int)height - textSize.Height) / 2);
drawing.RotateTransform(-45);
drawing.TranslateTransform(-((int)width - textSize.Width) / 2, -((int)height - textSize.Height) / 2);
//绘制背景
drawing.Clear(backColor);
//创建文本刷
Brush textBrush = new SolidBrush(textColor);
drawing.DrawString(text, font, textBrush, ((int)width - textSize.Width) / 2, ((int)height - textSize.Height) / 2);
drawing.Save();
return img;
}
}
/// <summary>
/// 签章参数
/// </summary>
public class PdfSignatureInfo
{
public PdfSignatureInfo()
{
}
/// <summary>
///
/// </summary>
public string PdfCertificatePath { get; set; }
/// <summary>
///
/// </summary>
public string PdfCertificatePathPwd { get; set; }
/// <summary>
///
/// </summary>
public string PdfSignatureName { get; set; }
/// <summary>
///
/// </summary>
public bool Certificated { get; set; }
/// <summary>
///
/// </summary>
public string ContactInfo { get; set; }
/// <summary>
///
/// </summary>
public string ContactInfoLabel { get; set; }
/// <summary>
///
/// </summary>
public DateTime Date { get; set; }
/// <summary>
///
/// </summary>
public string DateLabel { get; set; }
/// <summary>
///
/// </summary>
public string DigitalSigner { get; set; }
/// <summary>
///
/// </summary>
public string DigitalSignerLable { get; set; }
/// <summary>
///
/// </summary>
public string DistinguishedName { get; set; }
/// <summary>
///
/// </summary>
public string DistinguishedNameLabel { get; set; }
/// <summary>
///
/// </summary>
public bool IsConfiguerGraphicFilledBounds { get; set; }
/// <summary>
///
/// </summary>
public bool IsTag { get; set; }
/// <summary>
///
/// </summary>
public string LocationInfo { get; set; }
/// <summary>
///
/// </summary>
public string LocationInfoLabel { get; set; }
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public string NameLabel { get; set; }
/// <summary>
///
/// </summary>
public string Reason { get; set; }
/// <summary>
///
/// </summary>
public string ReasonLabel { get; set; }
/// <summary>
///
/// </summary>
public GraphicMode GraphicsMode { get; set; }
/// <summary>
/// 签章图片地址
/// </summary>
public string SignImageSourcePath { get; set; }
}
/// <summary>
///
/// </summary>
public class SpireTextWaterMarkPara
{
/// <summary>
///
/// </summary>
public SpireTextWaterMarkPara()
{
PdfFontFamily = PdfFontFamily.Helvetica;
PdfBrush = PdfBrushes.Blue;
PdfTextAlignment = PdfTextAlignment.Center;
Width = 0;
Height = 0;
XCoordinate = 0;
YCoordinate = 0;
}
/// <summary>
/// 水印文本
/// </summary>
public string WaterMarkText { get; set; }
/// <summary>
/// 透明度:0,10%,20%。。。。。90%,100%
/// 0,0.1f,0.2f,。。。。。0.9f,1
/// </summary>
public float Alpha { get; set; }
/// <summary>
/// 旋转度数
/// </summary>
public float RotateDegree { get; set; }
/// <summary>
/// 字体样式
/// </summary>
public PdfFontFamily PdfFontFamily { get; set; }
/// <summary>
/// 字体大小
/// </summary>
public int FontSize { get; set; }
/// <summary>
/// 文本颜色,获取Aqua....画笔
/// </summary>
public PdfBrush PdfBrush { get; set; }
/// <summary>
/// 指定文本对齐到...
/// </summary>
public PdfTextAlignment PdfTextAlignment { get; set; }
/// <summary>
/// PDF的左边距离
/// </summary>
public float Width { get; set; }
/// <summary>
/// PDF的上边距离
/// </summary>
public float Height { get; set; }
/// <summary>
/// X坐标
/// </summary>
public float XCoordinate { get; set; }
/// <summary>
/// Y坐标
/// </summary>
public float YCoordinate { get; set; }
}
}