简体   繁体   English

iTextSharp基于SQL查询编辑PDF

[英]iTextSharp edit PDF's based on SQL Query

I need to edit merging PDF's to have a colored bar on each PDF page based on a value in an SQL database where the PDF filename is also stored. 我需要根据要存储PDF文件名的SQL数据库中的值,对合并的PDF进行编辑,以使每个PDF页面上都有一个彩色条。 I am not great with C# lists but thought perhaps I could build a supplemental list to the iTextSharp "PDFReader" list then when iterating through the PDFReader list write a conditional statement that says "if list 2 value = "Utilities" then create green square" during the PDF merge process. 我对C#列表不太满意,但认为我可以为iTextSharp“ PDFReader”列表构建一个补充列表,然后在遍历PDFReader列表时写一条条件语句,说“如果列表2值=“实用程序”然后创建绿色方块”在PDF合并过程中。

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        if ((Session["AccessLevel"].ToString() == "admin") || (Session["AccessLevel"].ToString() == "worker") || (Session["AccessLevel"].ToString() == "client"))
        {
            if (Request.QueryString["type"] == "QC")
            {
                //SqlDataSource2.Update();
            }
            else
            {
            }

            string checkID = Request.QueryString["id"];

            SqlDataReader rdr = null;
            SqlConnection con2 = new SqlConnection(sqlConnection);
            con2.Open();
            //string sqlRowCount = "SELECT COUNT(*) FROM [Attachment] WHERE RequestId = '" + checkID + "' AND AttachType != 'Invoice' AND AttachType != 'Cover Sheet' ORDER BY AttachOrder ASC";
            sqlUserName2 = "SELECT  AttachmentName,AttachType FROM [Attachment] WHERE RequestId = '" + checkID + "' AND AttachType != 'Invoice' AND AttachType != 'Cover Sheet' ORDER BY AttachOrder ASC";
            //SqlCommand cmd = new SqlCommand(sqlRowCount, con2);
            //string count = cmd.ExecuteScalar().ToString();
            SqlCommand cmd2 = new SqlCommand(sqlUserName2, con2);
            rdr = cmd2.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Load(rdr);
            List<PdfReader> readerList = new List<PdfReader>();
            List<string> pdfName = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                PdfReader pdfReader = new PdfReader(Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/uploads/reports/" +
                  Convert.ToString(row[0])));

                readerList.Add(pdfReader);
                pdfName.Add(Convert.ToString(row[1]));
                //pdfName.Add(rdr["AttachType"].ToString());
            }

            System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
            contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Pdf;
            Document document = new Document(PageSize.A4, 0, 0, 40, 0);
            //Get instance response output stream to write output file.
            PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);

            // document.Header = new HeaderFooter(new Phrase("Header Text"), false);
            // Parameters passed on to the function that creates the PDF 
            String headerText = "";
            String footerText = "PAGE";

            // Define a font and font-size in points (plus f for float) and pick a color
            // This one is for both header and footer but you can also create seperate ones
            Font fontHeaderFooter = FontFactory.GetFont("arial", 12f);
            fontHeaderFooter.Color = Color.BLACK;

            // Apply the font to the headerText and create a Phrase with the result
            Chunk chkHeader = new Chunk(headerText, fontHeaderFooter);
            Phrase p1 = new Phrase(chkHeader);

            // create a HeaderFooter element for the header using the Phrase
            // The boolean turns numbering on or off
            HeaderFooter header = new HeaderFooter(p1, false);

            // Remove the border that is set by default
            header.Border = Rectangle.NO_BORDER;
            // Align the text: 0 is left, 1 center and 2 right.
            header.Alignment = 1;

            // add the header to the document
            document.Header = header;

            // The footer is created in an similar way

            // If you want to use numbering like in this example, add a whitespace to the
            // text because by default there's no space in between them
            if (footerText.Substring(footerText.Length - 1) != " ") footerText += " ";
            //string newFooter = footerText + pageCount;

            Chunk chkFooter = new Chunk(footerText, fontHeaderFooter);
            Phrase p2 = new Phrase(chkFooter);

            // Turn on numbering by setting the boolean to true
            HeaderFooter footer = new HeaderFooter(p2, true);
            footer.Border = Rectangle.NO_BORDER;
            footer.Alignment = 1;

            document.Footer = footer;
            Response.Write(pdfName);
            Response.Write("test");
            // Open the Document for writing and continue creating its content
            document.Open();
            foreach (PdfReader reader in readerList)
            {                   
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {

                    PdfImportedPage page = writer.GetImportedPage(reader, i);

                    if ("if list 2 value = "Utilities" then create green square")
                    {
                        PdfContentByte cb = writer.DirectContent;
                        var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
                        rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
                        rect.BorderWidth = 5; rect.BorderColor = new BaseColor(2, 3, 0);
                        cb.Rectangle(rect);
                    }
                    document.Add(iTextSharp.text.Image.GetInstance(page));
                }
            }
            document.Close();
            Response.AppendHeader("content-disposition", "inline; filename=" + Request.QueryString["id"] + "-Final");
            Response.ContentType = "application/pdf";
            con2.Close();
            Response.Write(pdfName);
        }
    }
    catch
    {
        // Response.Redirect("~/PDFProblem.aspx", false);
    }
}

This is a bit clunky but it works until I refactor it. 这有点笨拙,但是在我重构之前它是有效的。 I simply iterated the second list (pdfName) within the first iTextSharp one (pdfReader) using an incrementing integer to move the second list forward when the first list did: 我只是在第一个iTextSharp一个(pdfReader)中迭代第二个列表(pdfName),使用递增整数将第一个列表向前移动第二个列表:

 foreach (PdfReader reader in readerList)
            {                   
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    string totalValue = pdfName[nextOne].ToString();
                    PdfImportedPage page = writer.GetImportedPage(reader, i);

                    if (totalValue == "Permit")
                    {
                        PdfContentByte cb = writer.DirectContent;
                        var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
                        rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
                        rect.BorderWidth = 5; rect.BorderColor = new BaseColor(2, 3, 0);
                        cb.Rectangle(rect);
                    }
                    if (totalValue == "TaxBill")
                    {
                        PdfContentByte cb = writer.DirectContent;
                        var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
                        rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
                        rect.BorderWidth = 15; rect.BorderColor = new BaseColor(3, 2, 0);
                        cb.Rectangle(rect);
                    }
                    nextOne = nextOne + 1;
                    document.Add(iTextSharp.text.Image.GetInstance(page));
                }
            }

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

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