CSharp: Excel Convert Pdf

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
 * 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);
        }
 
    }
}

  

posted @   ®Geovin Du Dream Park™  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2013-07-18 jQuery plugin: Tablesorter 2.0
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示