CSharp: Excel Convert Pdf

发布时间 2023-07-18 22:37:31作者: ®Geovin Du Dream Park™

 

/**
 * net core 6
 * **/
using IronPdf;
using OfficeOpenXml;
using System.Text;

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Xls;


using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using iTextSharp.text;
using iTextSharp.text.pdf;




namespace App
{

    /// <summary>
    /// 
    /// </summary>
    public class ExcelHelper
    {


        /// <summary>
        /// 
        /// </summary>
        /// <param name="excelFilePath"></param>
        /// <param name="pdfFilePath"></param>
        public static void ConvertExcelToPdf(string excelFilePath, string pdfFilePath)
        {
            // 读取Excel文件
            using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFilePath)))
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; // 假设要转换的工作表是第一个工作表

                // 创建一个HTML字符串,将Excel内容转换为HTML
                string htmlContent = ExcelToHtml(worksheet);

                // 使用IronPDF将HTML字符串转换为PDF
                var renderer = new HtmlToPdf();
                renderer.PrintOptions.MarginTop = 0;
                renderer.PrintOptions.MarginBottom = 0;
                renderer.PrintOptions.MarginLeft = 0;
                renderer.PrintOptions.MarginRight = 0;
                var pdf = renderer.RenderHtmlAsPdf(htmlContent);

                // 保存PDF文件
                pdf.SaveAs(pdfFilePath);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="worksheet"></param>
        /// <returns></returns>
        public static string ExcelToHtml(ExcelWorksheet worksheet)
        {
            var sb = new StringBuilder();
            sb.AppendLine("<table>");
            var startRow = worksheet.Dimension.Start.Row;
            var endRow = worksheet.Dimension.End.Row;
            var startColumn = worksheet.Dimension.Start.Column;
            var endColumn = worksheet.Dimension.End.Column;

            for (int row = startRow; row <= endRow; row++)
            {
                sb.AppendLine("<tr>");

                for (int col = startColumn; col <= endColumn; col++)
                {
                    var cellValue = worksheet.Cells[row, col].Value;
                    sb.AppendLine("<td>" + (cellValue != null ? cellValue.ToString() : "") + "</td>");
                }

                sb.AppendLine("</tr>");
            }
            sb.AppendLine("</table>");
            return sb.ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="excelFilePath"></param>
        /// <param name="pdfFilePath"></param>
        public static void SprieConvertExcelToPdf(string excelFilePath, string pdfFilePath)
        {
            // 加载Excel文件
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(excelFilePath);
            // 创建PDF文档
            Spire.Pdf.PdfDocument pdfDocument = new Spire.Pdf.PdfDocument();
            // 添加Excel表格内容到PDF
            foreach (Worksheet sheet in workbook.Worksheets)
            {
                Spire.Pdf.PdfPageBase pdfPage = pdfDocument.Pages.Add();
                Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
                Spire.Pdf.Graphics.PdfTrueTypeFont fonts = new Spire.Pdf.Graphics.PdfTrueTypeFont(@"C:\Windows\Fonts\simfang.ttf", 10f);
                // 获取Excel表格的行数和列数
                int rowCount = sheet.LastRow + 1;
                int columnCount = sheet.LastColumn + 1;
                // 将Excel表格内容逐个添加到PDF
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int column = 1; column <= columnCount; column++)
                    {
                        string value = sheet.Range[row, column].Text;
                        if (value != null)
                        // 绘制单元格内容到PDF页面
                        {
                            pdfPage.Canvas.DrawString(value, fonts, PdfBrushes.Black, column * 70, row * 20);
                        }
                    }
                }
            }
            // 保存PDF文件
            pdfDocument.SaveToFile(pdfFilePath);
            Console.WriteLine("PDF转换完成。");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="excelFilePath"></param>
        /// <param name="pdfFilePath"></param>
        public static void ConvertExcelToPdf2(string excelFilePath, string pdfFilePath)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            // 加载Excel文件
            using (FileStream fileStream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = new XSSFWorkbook(fileStream);
                ISheet sheet = workbook.GetSheetAt(0);
                // 创建PDF文档
               iTextSharp.text.Document document = new iTextSharp.text.Document();
                // 创建PDF写入器
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(pdfFilePath, FileMode.Create));
                // 打开PDF文档
                document.Open();
                // 添加Excel表格内容到PDF
                iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(sheet.GetRow(0).LastCellNum);
                table.WidthPercentage = 100;

                foreach (IRow row in sheet)
                {
                    foreach (ICell cell in row)
                    {
                        string value = cell.ToString();
                        PdfPCell pdfCell = new PdfPCell(new Phrase(value, GetChineseFont()));
                        table.AddCell(pdfCell);
                    }
                }
                document.Add(table);
                // 关闭PDF文档
                document.Close();
            }
            Console.WriteLine("PDF转换完成。");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        static Font GetChineseFont()
        {
            var baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            return new Font(baseFont, 12);
        }

    }
}