专业的编程技术博客社区

网站首页 > 博客文章 正文

C#使用 aspose 从excel转成pdf(c# excel转pdf插件)

baijin 2024-08-14 12:18:16 博客文章 6 ℃ 0 评论

【实例简介】C#使用 aspose 从excel转成pdf,用矩阵处理其中的签章图片大小和位置

【实例截图】

【核心代码】

public Stream ExcelToPdf(Stream sm_excel)
{
Stream sm_Re = new MemoryStream();//返回的pdf结果
Stream sm_pdf = new MemoryStream();//返回的pdf结果
MemoryStream sm_img = new MemoryStream();//excel中原始图片信息
try
{
//加载excel文档
Aspose.Cells.Workbook wbc = new Aspose.Cells.Workbook(sm_excel);
//获取excel中原始签章图片信息
Aspose.Cells.Drawing.Picture pic = wbc.Worksheets[0].Pictures[0];
pic.Width = pic.OriginalWidth;
pic.Height = pic.OriginalHeight;
ImageOrPrintOptions printOption = new ImageOrPrintOptions(); //图片格式
printOption.ImageFormat = pic.ImageFormat;
pic.ToImage(sm_img, printOption);
//图片区域大小控制//zai pdf上显示 137像素,这里要设置成89,大概是这个比例,根据excel中签章原始大小设置
double lowerLeftX = 0, lowerLeftY = 0, upperRightX = pic.Width, upperRightY = pic.Height;
upperRightX = 137 * pic.Width / 280;
upperRightY = 137 * pic.Width / 280;
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
//处理excel-----------------------------------------------------------------------------------------------------------
//删除excel中的图片
wbc.Worksheets[0].Pictures.RemoveAt(0);
//把excel保存为pdf
Aspose.Cells.PdfSaveOptions op = new Aspose.Cells.PdfSaveOptions();
op.AllColumnsInOnePagePerSheet = false;
op.OnePagePerSheet = true;
wbc.Save(sm_pdf, op);
//处理pdf---------------------------------------------------------------------------------------------------------------
//给pdf添加签章
Document pdfDocument = new Document(sm_pdf);
PdfAddImage(pdfDocument, sm_img, rectangle);
pdfDocument.Save("D:\\00685.pdf");
pdfDocument.Save(sm_Re);
//资源释放
pdfDocument.Dispose();
sm_img.Close();
sm_pdf.Close();
return sm_Re;
}
catch(Exception ex)
{
//写日志
return sm_Re;
}
finally
{

}


}

public void PdfAddImage(Document pdfDocument, Stream sm_img, Aspose.Pdf.Rectangle rectangle)
{
try
{
//页面区域
Aspose.Pdf.Rectangle rec1 = pdfDocument.Pages[pdfDocument.Pages.Count].GetPageRect(true);
//签章位置 :跟页面 右 下 边缘的距离
double margin_right = 200, margin_bottom = 100;
//创建矩阵对象
Aspose.Pdf.DOM.Matrix matrix = new Aspose.Pdf.DOM.Matrix(rectangle.URX - rectangle.LLX, 0, 0, rectangle.LLY - rectangle.URY, rec1.URX -margin_right, rec1.URY -margin_bottom);
//找到添加签章的页面
Aspose.Pdf.Page page = pdfDocument.Pages[pdfDocument.Pages.Count];
//添加图片到页面资源
page.Resources.Images.Add(sm_img);
//保存当前图形状态
page.Contents.Add(new Operator.GSave());
//定义放置图像方式
page.Contents.Add(new Operator.ConcatenateMatrix(matrix));
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
//绘制图像
page.Contents.Add(new Operator.Do(ximage.Name));
//恢复图像状态
page.Contents.Add(new Operator.GRestore());
}
catch (Exception ex)
{
//写异常日志
}

}


本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表