如何用iText7在C#中配置PDF页面设置与边距并限制单页
使用iText7将HTML转换为带指定设置的单页PDF
需求说明
我正在开发一款应用,需将指定HTML转换为单页PDF。现有使用iText7的C#转换代码,需添加以下设置:
- DefaultEncoding = "utf-8"
- PaperSize = PaperKind.A4
- Orientation = Orientation.Portrait
- Margins = new MarginSettings { Top = 10, Bottom = 10 }
原HTML代码
string htmlContent = $@"<!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <meta name=""viewport"" content=""width=device-width, initial-scale=1.0""> </head> <body> <div style=""position: relative;""> <div style=""padding: 20px; padding-bottom: 0px;""> <img height=""80px"" width=""220px"" src=""{image1Url}"" alt="""" srcset=""""> <p style=""margin-top: -40pt;padding-left: 188pt;text-indent: 0pt;text-align: left;""> <span style="" color: #007E00; font-family:Arial, sans-serif; font-style: italic; font-weight: normal; font-size: 14pt;"">1</span> <span style="" color: #007E00; font-family:Arial, sans-serif; font-style: italic; font-weight: normal; font-size: 9pt; vertical-align: 4pt;"">ère</span> <span style="" color: #007E00; font-family:Arial, sans-serif; font-style: italic; font-weight: normal; font-size: 14pt;"">solution de paiement par mobile à Madagascar</span> </p> </div> <div style=""border-bottom: 20px solid #ffde00; margin-top: -5px;""></div> <div style=""padding: 20px;""> <div style=""margin-bottom: 20px;""> <h3>ATTESTATION DE TRANSFERT VIA MVOLA </h3> </div> <div style=""margin-bottom: 50px;""> <p style=""margin: 0px; margin-bottom: 5px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;""> {dto.Name}</p> <p style=""margin: 0px; margin-bottom: 5px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;""> Mobile : {dto.Msisdn}</p> <p style=""margin: 0px; margin-bottom: 5px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;""> E-mail : {dto.Email}</p> </div> <div style=""border-top: 3px solid #ffde00; border-bottom: 3px solid #ffde00; padding: 20px 0px; margin-bottom: 50px;""> <table style=""width: 100%;""> <thead> <tr> <th style=""text-align: start;"">Libellé</th> <th style=""text-align: start;"">Date</th> <th style=""text-align: start;"">Référence</th> <th style=""text-align: start;"">Montant</th> </tr> </thead> <tbody> <tr> <td style=""text-align: start;"">{dto.Description}</td> <td style=""text-align: start;"">{dto.TransDate}</td> <td style=""text-align: start;"">{dto.TransID}</td> <td style=""text-align: start;"">{dto.Amount} Ar</td> </tr> </tbody> </table> </div> <div style=""padding: 20px; margin-bottom: 40px;""> <p style=""margin: 0px; margin-bottom: 5px; font-size: 14px; font-family: Arial, Helvetica, sans-serif;""> À conserver pour vos archives</p> <h3 style=""margin-bottom: 40px;"">TOUJOURS PLUS SIMPLE AVEC MVOLA!</h3> <div style=""style=""height: 700px;""> <img src=""{image2Url}"" alt="""" height=""auto"" width=""100%"" style=""max-height: 600px;""> </div> </div> </div> <div style=""margin-bottom: 20px; padding: 20px; background-color: #ffde00;""> <table style=""width: 100%;""> <tbody> <tr> <td style=""width: 50%; text-align: start;""> <div style=""margin-bottom: 10px; color: #007E00;""> <p style="" margin: 0px; margin-bottom: 5px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;""> Service Client MVola : 807</p> <p style=""margin: 0px; margin-bottom: 5px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;""> E-mail : <a href=""mailto:mvola@telma.mg"">mvola@telma.mg</a></p> <p style=""margin: 0px; margin-bottom: 5px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;""> <a href=""http://www.mvola.mg/MVola_mobile_money.php""> www.mvola.mg</a> </p> </div> </td> <td style=""width: 50%; text-align: end;""> <div> <img src=""{image3Url}"" alt="""" srcset="""" height=""80px"" width=""220px""> </div> </td> </tr> </tbody> </table> </div> </div> </body> </html>";
原C#代码
public string GeneratePdfFromHtmlAndConvertToBase64(string htmlContent) { try { string base64String; _logger.LogInformation($"Request ID: {_localSessionManager.InternalTransectionSessionID} - GeneratePdfFromHtmlAndConvertToBase64, Request: {htmlContent}"); using (var memoryStream = new MemoryStream()) { var writerProperties = new WriterProperties(); using (var pdfWriter = new PdfWriter(memoryStream, writerProperties)) { using (var pdfDocument = new PdfDocument(pdfWriter)) { var doc = new Document(pdfDocument); doc.SetMargins(10, 10, 10, 10); pdfDocument.SetDefaultPageSize(PageSize.A4); HtmlConverter.ConvertToPdf(htmlContent, pdfDocument, new ConverterProperties()); } } var bytes = memoryStream.ToArray(); base64String = Convert.ToBase64String(bytes); } _logger.LogInformation($"Request ID: {_localSessionManager.InternalTransectionSessionID} - GeneratePdfFromHtmlAndConvertToBase64, base64String: {base64String}"); return base64String; } catch (Exception ex) { _logger.LogError(ex, $"Request ID: {_localSessionManager.InternalTransectionSessionID} - GeneratePdfFromHtmlAndConvertToBase64, Exception Occurred: {ex.Message}"); return null; } }
修改后的C#代码及说明
要满足所有指定设置,需对ConverterProperties进行配置,并调整页面相关设置:
- UTF-8编码:通过
ConverterProperties.SetCharset("utf-8")指定编码; - A4纵向纸张:
PageSize.A4默认即为纵向,直接设置为默认页面大小即可; - 上下边距10:通过
MarginSettings设置上下边距,左右边距可根据需求调整; - 移除原代码中
doc.SetMargins(...),避免与HTML转换的边距设置冲突。
修改后的完整代码:
public string GeneratePdfFromHtmlAndConvertToBase64(string htmlContent) { try { string base64String; _logger.LogInformation($"Request ID: {_localSessionManager.InternalTransectionSessionID} - GeneratePdfFromHtmlAndConvertToBase64, Request: {htmlContent}"); using (var memoryStream = new MemoryStream()) { var writerProperties = new WriterProperties(); using (var pdfWriter = new PdfWriter(memoryStream, writerProperties)) { using (var pdfDocument = new PdfDocument(pdfWriter)) { // 设置A4纵向为默认页面大小 pdfDocument.SetDefaultPageSize(PageSize.A4); // 配置转换属性 var converterProperties = new ConverterProperties() // 设置UTF-8编码 .SetCharset("utf-8") // 设置边距:上下10,左右可按需调整 .SetMarginSettings(new MarginSettings { Top = 10, Bottom = 10, Left = 0, Right = 0 }); // 执行HTML转PDF HtmlConverter.ConvertToPdf(htmlContent, pdfDocument, converterProperties); } } var bytes = memoryStream.ToArray(); base64String = Convert.ToBase64String(bytes); } _logger.LogInformation($"Request ID: {_localSessionManager.InternalTransectionSessionID} - GeneratePdfFromHtmlAndConvertToBase64, base64String: {base64String}"); return base64String; } catch (Exception ex) { _logger.LogError(ex, $"Request ID: {_localSessionManager.InternalTransectionSessionID} - GeneratePdfFromHtmlAndConvertToBase64, Exception Occurred: {ex.Message}"); return null; } }
内容的提问来源于stack exchange,提问作者Kamran Khan
相关产品推荐
相关产品推荐

