微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 iText7 和 ASP NET C#

如何解决使用 iText7 和 ASP NET C#

这是数据库 t_contents_2021 上的表 MysqL version 8.0.17

-- ----------------------------
-- Table structure for t_contents_2021
-- ----------------------------
DROP TABLE IF EXISTS `t_contents_2021`;
CREATE TABLE `t_contents_2021`  (
  `contents` varchar(1000)  DEFAULT NULL,`sUnity` varchar(255)  DEFAULT NULL,`sID_content_image` varchar(255)  DEFAULT NULL,`sID_content_image_link` varchar(255)  DEFAULT NULL,`sID_content_ppt` varchar(255)  DEFAULT NULL,`sID_content_ppt_link` varchar(255)  DEFAULT NULL,`sID_content_xls` varchar(255)  DEFAULT NULL,`sID_content_xls_link` varchar(255)  DEFAULT NULL,`sID_content_pdf` varchar(255)  DEFAULT NULL,`sID_content_pdf_link` varchar(255)  DEFAULT NULL,`sID` int(11) NOT NULL AUTO_INCREMENT,PRIMARY KEY (`sID`) USING BTREE,UNIQUE INDEX `contents`(`contents`) USING BTREE
) ENGINE = InnoDB;

-- ----------------------------
-- Records of t_contents_2021
-- ----------------------------
INSERT INTO `t_contents_2021` VALUES ('Set 1','Q400',NULL,1);
INSERT INTO `t_contents_2021` VALUES ('- Par 1.1',2);
INSERT INTO `t_contents_2021` VALUES ('<b>bold text</b>',3);
INSERT INTO `t_contents_2021` VALUES ('- Par 1.2',4);
INSERT INTO `t_contents_2021` VALUES ('normal text',5);
INSERT INTO `t_contents_2021` VALUES ('Set 2',6);
INSERT INTO `t_contents_2021` VALUES ('- Par 2.1',7);
INSERT INTO `t_contents_2021` VALUES ('<i>italic text</i>',8);
INSERT INTO `t_contents_2021` VALUES ('- Par 2.2',9);
INSERT INTO `t_contents_2021` VALUES ('<u>underline text</u>',10);

在字段 t_contents_2021 的表 contents 上有一些 html 代码

<b>bold text</b>
<i>italic text</i>
<u>underline text</u>

现在我使用 iText (Version 7.1.13) 将 html 转换为 pdf 使用 HtmlConverter (html2pdf version 2.0.1)

string filename;
string html;
string dest;

Paragraph contents;

protected void Page_Load(object sender,EventArgs e)
{
    PdfWriter writer = new PdfWriter(Response.OutputStream);
    PdfDocument pdf = new PdfDocument(writer);
    Document document = new Document(pdf);

    using (MysqLConnection cn =
        new MysqLConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {

        using (MysqLCommand cmd =
            new MysqLCommand("SP",cn))
        {
            cmd.Connection.open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("tunity","Q400");

            MysqLDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    contents = new Paragraph(reader.GetString("contents"))
                    .SetTextAlignment(TextAlignment.JUSTIFIED)
                    .SetFontSize(12);

                    if (reader.GetString("contents").StartsWith("Set"))
                    {
                        contents.SetFontSize(12)
                            .SetBold()
                            .SetFontColor(ColorConstants.BLUE);
                        document.Add(newline);
                    }
                    else if (reader.GetString("contents").StartsWith("- "))
                    {
                        contents.SetFontSize(10)
                            .SetBold()
                            .SetFontColor(ColorConstants.BLACK);
                        document.Add(newline);
                    }
                    else
                    {
                        contents.SetFontSize(10)
                            .SetFontColor(ColorConstants.BLACK);
                    }

                    if (!String.IsNullOrEmpty(reader["sID_content_image"].ToString()))
                    {
                        Image image_path = new Image(ImageDataFactory
                              .Create(reader["sID_content_image"].ToString()))
                              .SetTextAlignment(TextAlignment.CENTER);

                        image_path.SetAutoScale(false);
                        image_path.SetBorderLeft(new SolidBorder(ColorConstants.DARK_GRAY,2));
                        image_path.SetBorderRight(new SolidBorder(ColorConstants.DARK_GRAY,2));
                        image_path.SetBorderTop(new SolidBorder(ColorConstants.DARK_GRAY,2));
                        image_path.SetBorderBottom(new SolidBorder(ColorConstants.DARK_GRAY,2));
                        document.Add(image_path);
                    }

                    if (!String.IsNullOrEmpty(reader["sID_content_ppt"].ToString()))
                    {
                        string IMG1 = "C:\\inetpub\\wwwroot\\aspnet\\img\\powerpoint-png-picture-2.jpg";
                        Image img1 = new Image(ImageDataFactory.Create(IMG1));
                        Table tablelink = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth();
                        PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

                        Cell cell = new Cell().Add(img1.SetAutoScale(false));
                        cell.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                        img1.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                        cell.SetBorder(Border.NO_BORDER);

                        cell.SetAction(PdfAction.CreateURI(
                            reader["sID_content_ppt_link"].ToString()));
                        tablelink.AddCell(cell);
                        document.Add(tablelink);
                        document.Add(newline);
                    }

                    if (!String.IsNullOrEmpty(reader["sID_content_xls"].ToString()))
                    {
                        string IMG1 = "C:\\inetpub\\wwwroot\\img\\excel-2.png";
                        Image img1 = new Image(ImageDataFactory.Create(IMG1));
                        Table tablelink = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth();
                        PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
                        Cell cell = new Cell().Add(img1.SetAutoScale(false));
                        cell.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                        img1.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                        cell.SetBorder(Border.NO_BORDER);
                        cell.SetAction(PdfAction.CreateURI(
                            reader["sID_content_xls_link"].ToString()));
                        tablelink.AddCell(cell);
                        document.Add(tablelink);
                        document.Add(newline);
                    }

                    if (!String.IsNullOrEmpty(reader["sID_content_pdf"].ToString()))
                    {
                        string IMG1 = "C:\\inetpub\\wwwroot\\img\\pdf-png-picture-2.gif";
                        Image img1 = new Image(ImageDataFactory.Create(IMG1));
                        Table tablelink = new Table(UnitValue.CreatePercentArray(1)).UseAllAvailableWidth();
                        PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
                        Cell cell = new Cell().Add(img1.SetAutoScale(false));
                        cell.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                        img1.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                        cell.SetBorder(Border.NO_BORDER);
                        cell.SetAction(PdfAction.CreateURI(
                            reader["sID_content_pdf_link"].ToString()));
                        tablelink.AddCell(cell);
                        document.Add(tablelink);
                        document.Add(newline);
                    }

                    document.Add(contents);
                }

                filename = @"C:\\inetpub\\wwwroot\\public\\Management_" + Guid.NewGuid() + ".pdf";
                html = contents.ToString();
                dest = filename.ToString();
                HtmlConverter.ConvertToPdf(html,new FileStream(dest,FileMode.Create));
            }
            else
            {
                Console.WriteLine("No rows found.");
            }

            reader.Close();
            cmd.Connection.Close();
        }
    }

    document.Close();

    Response.Clear();
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-disposition","attachment; filename=" + dest);
    Response.TransmitFile(dest);
    Response.End();
}

生成的 pdf 文件 Management_14a40257-547f-4b6f-b991-eaa4aeb47a9a.pdf 不包含表 t_contents_2021 中的值,但仅包含此文本:

enter image description here

如果不在我的代码中使用 HtmlConverter.ConvertToPdf

filename = @"C:\\inetpub\\wwwroot\\public\\Management_" + Guid.NewGuid() + ".pdf";
html = contents.ToString();
dest = filename.ToString();
HtmlConverter.ConvertToPdf(html,FileMode.Create));
        

pdf 文件已正确创建,但在 pdf 上我有

enter image description here

帮我搞定

这是 MysqL 中的 Stored procedure

CREATE DEFINER=`root`@`localhost` PROCEDURE `SP`(IN tunity CHAR(100))
BEGIN

SET @s = CONCAT('SELECT * FROM t_contents_2021 WHERE sUnity = \'',tunity,'\';');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE `stmt`;

END

解决方法

这行代码有误:

;

html = contents.ToString(); 是一个 contents 对象;对其调用 iText.Layout.Element.Paragraph 会返回类型的名称。将该字符串转换为 PDF 会产生您看到的输出。

您需要找到另一个 API 来将 .ToString() 保存为 PDF。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。