简体   繁体   English

从包含 html 代码的 MySql 表中创建 pdf 文件,使用 iText7 和 ASP NET ZD7EFA19FBE242236

[英]Create pdf file from MySql table containing html code using iText7 and ASP NET C#

This is table t_contents_2021 on database MySql version 8.0.17这是数据库MySql version 8.0.17上的表t_contents_2021

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

On the table t_contents_2021 in field contents there is some html code在字段contents的表t_contents_2021上有一些 html 代码

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

Now I use iText (Version 7.1.13) to convert html to pdf using HtmlConverter (html2pdf version 2.0.1)现在我使用iText(版本 7.1.13)将 html 转换为 pdf 使用HtmlConverter(html2pdf 版本 2.0.

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();
}

The generated pdf file Management_14a40257-547f-4b6f-b991-eaa4aeb47a9a.pdf doesn't contains the values from table t_contents_2021 but contains only this text:生成的 pdf 文件Management_14a40257-547f-4b6f-b991-eaa4aeb47a9a.pdf不包含表t_contents_2021中的值,但仅包含此文本

在此处输入图像描述

If not use on my code the HtmlConverter.ConvertToPdf如果不在我的代码上使用 HtmlConverter.ConvertToPdf

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

the pdf file is created correctly but on pdf I have pdf 文件已正确创建,但在 pdf 上我有

在此处输入图像描述

Help me to do it帮我做

This is the Stored procedure in MySql这是 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

This line of code is wrong:这行代码是错误的:

html = contents.ToString();

contents is a iText.Layout.Element.Paragraph object; contentsiText.Layout.Element.Paragraph object; calling .ToString() on it returns the name of the type.对其调用.ToString()会返回类型的名称。 Converting that string to PDF produces the output you see.将该字符串转换为 PDF 会产生您看到的 output。

You need to find another API to save document to a PDF.您需要找到另一个 API 将document保存到 PDF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM