iTextSharp редактировать PDF на основе SQL-запросов - PullRequest
0 голосов
/ 01 марта 2019

Мне нужно отредактировать объединяющиеся PDF-файлы, чтобы на каждой PDF-странице была цветная полоса на основе значения в базе данных SQL, где также хранится имя файла PDF.Я не очень хорош в списках C #, но подумал, что, возможно, я мог бы создать дополнительный список к списку iTextSharp "PDFReader", а затем при переборе списка PDFReader написать условный оператор, который говорит: "если list 2 value =" Utilities ", тогда создайте зеленый квадрат"в процессе слияния 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);
    }
}

1 Ответ

0 голосов
/ 01 марта 2019

Это немного неуклюже, но это работает, пока я не рефакторинг.Я просто перебрал второй список (pdfName) внутри первого списка iTextSharp (pdfReader), используя приращающееся целое число для перемещения второго списка вперед, когда первый список это сделал:

 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));
                }
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...