天天看点

C# 将Excel导出PDF

1、安装所需包,使用nuget安装所需包

  1.1、Spire.Xls

  1.2、iTextSharp.text.pdf

2、Spire.Xls介绍

  将Excel转换为PDF是一个很常用的功能,常见的转换场景有以下三种:

 2.1、转换整个Excel文档到PDF

 2.2、转换Excel文档的某一个工作表到PDF

 2.3、转换Excel文档的某一个工作表的某一部分单元格到PDF

 ps:Spire是收费,所以导出excel有如下字样。

C# 将Excel导出PDF
解决方法:使用空白图片对字样覆盖操作即可。

//方法一
Workbook workbook = new Workbook();
workbook.LoadFromFile("示例.xlsx");
workbook.SaveToFile("输出.pdf", FileFormat.PDF);

//方法二、对excel某一个sheet生成pdf
Workbook workbook = new Workbook();
workbook.LoadFromFile("示例.xlsx");
Worksheet sheet = workbook.Worksheets[0];
sheet.SaveToPdf("输出1.pdf");      

3、使用空白图片对字样pdf进行覆盖操作

private void Excel2PDF(string resourcePdfPath)
        {
          
            
            Workbook workbook = new Workbook();
            //加载excel文件
            workbook.LoadFromFile("excel路径");
            Worksheet sheet = workbook.Worksheets[0];
            //使用spire生成pdf
            sheet.SaveToPdf(resourcePdfPath);
            stream.Close();
        }
        //利用空白图片去掉上图红字字样
        private void AddImgToPDF(string resourcePdfPath,string savePdfPath ,string blackImgPath)
        {
           //加载有字样的pdf模板
            PdfReader reader = new PdfReader(resourcePdfPath);
            PdfStamper pdfStamper = new PdfStamper(reader, new FileStream(savePdfPath, FileMode.Create));
            int iPageNum = reader.NumberOfPages; //pdf页面数
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            string imagePath = blackImgPath;
            //加载空白图片
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath); 
            //设置空白图片位置
            img.SetAbsolutePosition(0, 800);
            //对pdf每页进行空白填充
            for (int j = 1; j <= iPageNum; j++)
            {
                PdfContentByte over = pdfStamper.GetOverContent(j);
                over.AddImage(img);
            }
            pdfStamper.Close();
            reader.Close();
        }

        private string ExportPDF(string pdfName)
        {
            string tempDirPath = Server.MapPath("/Templates/Excel/");
            string tempPdfPath = tempDirPath + DateTime.Now.ToFileTime() + ".pdf";
            Excel2PDF(tempPdfPath);
            string blackImgPath = tempDirPath + "black.png";
            string savePdfPath = tempDirPath + pdfName + ".pdf";
            AddImgToPDF(tempPdfPath, savePdfPath, blackImgPath);
            FileInfo file = new FileInfo(tempPdfPath);
            file.Delete();
            return savePdfPath;
        }