简体   繁体   English

使用 iTextSharp 将文本、图像、图片和条形码添加到 PDF

[英]Adding text, images, pictures and barcodes to a PDF using iTextSharp

Maybe I am making this harder than it is, but I am having a heck of time getting everything to layout together, or even appear on my pdf.也许我做得比现在更难,但我有很多时间把所有东西都放在一起,甚至出现在我的 pdf 上。

In my code, CreatePdf is called a single time for creation of a badge front, then a single time for the badge back.在我的代码中, CreatePdf 被称为单次创建徽章正面,然后是徽章背面的单次。 All the object parts of the pdf are stored in a database, and are then looped through in this method. pdf 的所有对象部分都存储在数据库中,然后在此方法中循环。

The original method only used the 'graph' object to create the pdf, with barcodes generated with the iText CreateDrawingImage which worked great...EXCEPT all the barcodes were quite blurry.原始方法仅使用“图形”对象来创建 pdf,使用 iText CreateDrawingImage 生成的条码效果很好......除了所有条码都非常模糊。 To combat this, the method was changed to use both the graph object and the iText Image, using CreateImageWithBarcode.为了解决这个问题,使用 CreateImageWithBarcode 将方法更改为同时使用图形对象和 iText 图像。

The problem is, that no matter what I do with iText image, it does not layout where I want it to on the pdf.问题是,无论我对 iText 图像做什么,它都不会在 pdf 上布局我想要的位置。 The barcode is supposed to be at the bottom of the badge, but with the iText image, the barcode moves itself to the top of the pdf, over the top of the graph items.条形码应该在徽章的底部,但是对于 iText 图像,条形码会移动到 pdf 的顶部,在图形项目的顶部。

When I changed all the different item types to all use iText image, nothing laid out correctly, or even showed on the pdf.当我将所有不同的项目类型更改为全部使用 iText 图像时,没有任何内容正确布局,甚至没有显示在 pdf 上。

I would prefer to use the graph to lay it all out, but the result of iText CreateDrawingImage is unusable.我更愿意使用图形来布置它,但是 iText CreateDrawingImage 的结果是不可用的。 Below in the switch statement, 'C128', 'Code39' and 'I25' are the items I am having trouble with.在 switch 语句的下方,“C128”、“Code39”和“I25”是我遇到问题的项目。 If anybody knows how I can get around these issues to layout a clean badge, it would be MUCH appreciated.如果有人知道我如何解决这些问题以布置干净的徽章,将不胜感激。 If there is a clean way of making CreateDrawingImage create a crisp barcode, it would be preferred.如果有一种干净的方法可以让 CreateDrawingImage 创建清晰的条形码,那将是首选。

Developing this in VS 2019 C#, using iTextSharp 5.5.13.1在 VS 2019 C# 中开发,使用 iTextSharp 5.5.13.1

    private byte[] CreatePDF(BadgeLayoutDTO badgeLayout, Document doc, PdfContentByte cb)
    {
        if (badgeLayout == null)
            return null;

        var width = Convert.ToInt32(badgeLayout.Width);
        var height = Convert.ToInt32(badgeLayout.Height);

        var offset = -50;

        // Create the new bitmap
        using (Image image = new Bitmap(width, height))
        {
            var graph = Graphics.FromImage(image);

            // Draw a border around the badge if specified
            if (badgeLayout.Outline > 0)
            {
                var pen = new Pen(Brushes.Black, badgeLayout.Outline);
                graph.DrawRectangle(pen, 0, 0, width - 1, height - 1);
            }

            foreach (var field in badgeLayout.BdgFieldList.OrderBy(x => x.FldPosition.FldTop))
            {
                var x = Convert.ToInt32(field.FldPosition.FldLeft * RatioHorz + badgeLayout.OffsetHorz / 2);
                var y = Convert.ToInt32(field.FldPosition.FldTop * RatioVert + badgeLayout.OffsetVert / 2);
                var w = Convert.ToInt32((field.FldPosition.FldRight - field.FldPosition.FldLeft) * RatioHorz);
                var h = Convert.ToInt32((field.FldPosition.FldBottom - field.FldPosition.FldTop) * RatioVert);

                switch (field.FldType)
                {
                    case "ShadedRoundRectangle":
                    case "RoundRect":
                    {
                        const float xradius = 5;
                        const float yradius = 5;
                        var brush = new SolidBrush(AccessToHex(field.FldColor.BkColor)); // Fill Color
                        var pen = new Pen(AccessToHex(field.FldColor.ForeColor),
                            field.FldPosition.FldSize + 3); // Border color
                        var rect = new System.Drawing.Rectangle(x, y, w, h);

                        using (pen)
                        {
                            var path = MakeRoundedRect(rect, xradius, yradius, true, true, true, true);
                            graph.FillPath(brush, path);
                            graph.DrawPath(pen, path);
                        }

                        break;
                    }
                    case "ShadeRect":
                    {
                        var brush = new HatchBrush(HatchStyle.Cross, AccessToHex(field.FldColor.BkColor - 100),
                            AccessToHex(field.FldColor.BkColor));
                        var pen = new Pen(AccessToHex(field.FldColor.ForeColor),
                            field.FldPosition.FldSize + 3); // Border color
                        var rect = new System.Drawing.Rectangle(x, y, w, h);
                        graph.DrawRectangle(pen, rect);
                        graph.FillRectangle(brush, rect);

                        break;
                    }
                    case "Rectangle":
                    {
                        var brush = new SolidBrush(AccessToHex(field.FldColor.BkColor));
                        var pen = new Pen(AccessToHex(field.FldColor.ForeColor),
                            field.FldPosition.FldSize + 3); // Border color
                        var rect = new System.Drawing.Rectangle(x, y, w, h);
                        graph.DrawRectangle(pen, rect);
                        graph.FillRectangle(brush, rect);

                        break;
                    }
                    case "Ellipse":
                    {
                        var brush = new SolidBrush(AccessToHex(field.FldColor.BkColor));
                        var pen = new Pen(AccessToHex(field.FldColor.ForeColor),
                            field.FldPosition.FldSize + 3); // Border color
                        var rect = new System.Drawing.Rectangle(x, y, w, h);
                        graph.DrawEllipse(pen, rect);
                        graph.FillEllipse(brush, rect);

                        break;
                    }
                    case "ShadedEllipse":
                    {
                        var brush = new HatchBrush(HatchStyle.Cross, AccessToHex(field.FldColor.BkColor - 100),
                            AccessToHex(field.FldColor.BkColor));
                        var pen = new Pen(AccessToHex(field.FldColor.ForeColor),
                            field.FldPosition.FldSize + 3); // Border color
                        var rect = new System.Drawing.Rectangle(x, y, w, h);
                        graph.DrawEllipse(pen, rect);
                        graph.FillEllipse(brush, rect);

                        break;
                    }
                    case "Image":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                            var dbimage = _filePicture.Get(field.FldData.FldDataValue.ToString(), 36);

                            //var imageJ = iTextSharp.text.Image.GetInstance(dbimage.FileImage);
                            //imageJ.SetAbsolutePosition(x, y + offset);

                            //var rect = new Rectangle(0, 0, w, h);
                            //imageJ.ScaleToFit(rect);

                            //doc.Add(imageJ);

                            using (var ms = new MemoryStream(dbimage.FileImage))
                            {
                                var newImage = Image.FromStream(ms);

                                // Resize image to proper aspect ratio
                                var aspect = ResizeKeepAspect(newImage.Size, w, h);
                                var aspectImage = ResizeImage(newImage, new Size(aspect.Width, aspect.Height));

                                // Create Point for upper-left corner of image.
                                var ulCorner = new Point(x, y);

                                // Draw image to screen.
                                graph.DrawImage(aspectImage, ulCorner);
                            }

                            break;
                    }
                    case "QRCode":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                        QRCodeGenerator qrGenerator = new QRCodeGenerator();
                        QRCodeData qrCodeData = qrGenerator.CreateQrCode(field.FldData?.FldDataValue.ToString(), QRCodeGenerator.ECCLevel.Q);
                        QRCode qrCode = new QRCode(qrCodeData);
                        Bitmap dbImage = qrCode.GetGraphic(20);
                        var aspect = ResizeKeepAspect(dbImage.Size, w, h);
                        var aspectImage = ResizeBadgeImage(dbImage, new Size(aspect.Width, aspect.Height));
                        using (var ms2 = new MemoryStream())
                        {
                            try
                            {
                                aspectImage.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                                var signatureImage = iTextSharp.text.Image.GetInstance(ms2.ToArray());
                                signatureImage.SetAbsolutePosition(x, y + offset - 100);
                                doc.Add(signatureImage);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                            }
                        }
                        break;
                    }
                    case "C128":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                        var dbImage = (new Barcode128()
                        {
                            Code = field.FldData?.FldDataValue.ToString()
                        });

                        iTextSharp.text.Image image128 = dbImage.CreateImageWithBarcode(cb, null, BaseColor.WHITE);
                        image128.SetAbsolutePosition(x, y + offset);
                        var rect = new Rectangle(0, 0, w, h);
                        image128.ScaleToFit(rect);
                        doc.Add(image128);
                        break;
                    }
                    case "Code39":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                        var dbImage = (new Barcode39
                        {
                            Code = field.FldData?.FldDataValue.ToString()
                        });

                        iTextSharp.text.Image image128 = dbImage.CreateImageWithBarcode(cb, null, BaseColor.WHITE);
                        image128.SetAbsolutePosition(x, y + offset);
                        var rect = new Rectangle(0, 0, w, h);
                        image128.ScaleToFit(rect);

                        doc.Add(image128);
                        break;
                    }
                    case "I25":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                        var dbImage = (new BarcodeInter25()
                        {
                            Code = field.FldData?.FldDataValue.ToString()
                        });

                        iTextSharp.text.Image image128 = dbImage.CreateImageWithBarcode(cb, null, BaseColor.WHITE);
                        image128.SetAbsolutePosition(x, y + offset);

                        var rect = new Rectangle(0, 0, w, h);
                        image128.ScaleToFit(rect);

                        doc.Add(image128);
                        break;
                    }
                    case "Picture":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                        var dbimage = _filePicture.Get(field.FldData.FldDataValue.ToString(), 48);

                        //var imageJ = iTextSharp.text.Image.GetInstance(dbimage.FileImage);
                        //imageJ.SetAbsolutePosition(x, y + offset);

                        //var rect = new Rectangle(0, 0, w, h);
                        //imageJ.ScaleToFit(rect);

                        //doc.Add(imageJ);
                        using (var ms = new MemoryStream(dbimage.FileImage))
                        {
                            var newImage = Image.FromStream(ms);

                            // Resize image to proper aspect ratio
                            var aspect = ResizeKeepAspect(newImage.Size, w, h);
                            var aspectImage = ResizeImage(newImage, new Size(aspect.Width, aspect.Height));

                            //var rect = new Rectangle(0, 0, w, h);

                            // Create Point for upper-left corner of image.
                            var ulCorner = new Point(x, y);

                            // Draw image to screen.
                            graph.DrawImage(aspectImage, ulCorner);
                        }

                        break;
                    }
                    case "Signature":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                        var dbimage = _filePicture.Get(field.FldData.FldDataValue.ToString(), 36);

                        if (dbimage == null) continue;

                            //iTextSharp.text.Image imageJ = new Jpeg(dbimage.FileImage);
                            //imageJ.SetAbsolutePosition(x, y + offset);

                            //var rect = new Rectangle(0, 0, w, h);
                            //imageJ.ScaleToFit(rect);

                            //doc.Add(imageJ);

                        using (var ms = new MemoryStream(dbimage.FileImage))
                        {
                            var newImage = Image.FromStream(ms);

                            // Resize image to proper aspect ratio
                            var aspect = ResizeKeepAspect(newImage.Size, w, h);
                            var aspectImage = ResizeImage(newImage, new Size(aspect.Width, aspect.Height));

                            // Create Point for upper-left corner of image.
                            var ulCorner = new Point(x, y);

                            // Draw image to screen.
                            graph.DrawImage(aspectImage, ulCorner);
                        }

                        break;
                    }
                    case "TextCenter":
                    case "TextLeft":
                    case "TextRight":
                    {
                            var text = GetText(field);

                            // Assume here that screen DPI is 96...
                            // If DPI is different, rendering issues might occur...
                            // Badge designer in Desktop assumes 300 DPI
                            var fontSizeDpiRatioFix = 300 / 96; //HACK
                            var fontSize = -field.FldPosition.FldSize * fontSizeDpiRatioFix * 1.03;
                            Font font;
                            try
                            {
                                font = FindFont(graph, text, new Size(w, h),
                                    new Font(new FontFamily(field.FldFont.FontName), (float)fontSize,
                                        GetFontParam(field.FldFont.FontParms)));
                            }
                            catch (Exception exc)
                            {
                                font = System.Drawing.SystemFonts.DefaultFont;
                            }

                            //Create rectangles
                            var rect1 = new System.Drawing.Rectangle(x, y, w, h);

                            //Construct string format and alignment
                            var strFormat1 = new StringFormat
                            {
                                Alignment = StringAlignment.Center,
                                LineAlignment = StringAlignment.Center,
                                Trimming = StringTrimming.EllipsisCharacter
                            };

                            // Draw GDI+ objects
                            graph.DrawRectangle(new Pen(Color.Transparent), rect1);
                            graph.DrawString(text, font,
                                new SolidBrush(AccessToHex(field.FldColor.ForeColor)), rect1, strFormat1);

                            //Disposes of objects
                            font.Dispose();

                            break;
                        }
                }
            }

            using (var ms = new MemoryStream())
            {
                image.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }

Instead of continuing the battle with iTextSharp barcodes, I instead installed IronBarCodes from Nugget, and was quickly able to get a crisp, clean barcode with only a couple lines of code.我没有继续使用 iTextSharp 条码,而是安装了来自 Nugget 的 IronBarCodes,并且很快就能获得清晰、干净的条码,只需几行代码。 The resulting barcode has the ability to export as a Bitmap, allowing me to use the Graphic layout that the rest of the pdf is using.生成的条形码能够导出为位图,允许我使用 pdf 其余部分使用的图形布局。 Problem solved.问题解决了。

Solution snippet:解决方案片段:

                    case "C128":
                    {
                        if (field.FldData?.FldDataValue == null)
                            continue;

                        var myBarCode = BarcodeWriter.CreateBarcode(field.FldData?.FldDataValue.ToString(), BarcodeEncoding.Code128)
                            .ResizeTo(w,h).ToBitmap();

                        // Create Point for upper-left corner of image.
                        var ulCorner = new Point(x, y);

                        // Draw image to screen.
                        graph.DrawImage(myBarCode, ulCorner);
                        break;
                    }

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

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