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有如下字樣。

 

解決方法:使用空白圖片對字樣覆蓋操作即可。

 

//方法一
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;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM