C# 使用iTextSharp将文本、图像、图片和条形码添加到PDF
也许我把这件事弄得更难了,但我花了很长时间把所有的东西都安排在一起,甚至出现在我的pdf上 在我的代码中,CreatePdf被称为一次性创建徽章正面,然后一次性创建徽章背面。pdf的所有对象部分都存储在数据库中,然后在此方法中循环 最初的方法只使用“graph”对象创建pdf,使用iText CreateDrawingImage生成的条形码效果非常好……除了所有的条形码都非常模糊之外。为了解决这个问题,该方法被更改为同时使用graph对象和iText图像,使用CreateImageWithBarcode 问题是,无论我如何处理iText图像,它都不会在pdf上按我希望的位置进行布局。条形码应该位于徽章的底部,但在iText图像中,条形码会移动到pdf的顶部,即图形项目的顶部 当我将所有不同的项目类型更改为全部使用iText图像时,没有任何正确的布局,甚至在pdf上也没有显示 我更愿意使用图表来展示一切,但iText CreateDrawingImage的结果无法使用。下面的switch语句中,“C128”、“Code39”和“I25”是我遇到问题的项。如果有人知道我如何绕过这些问题来设计一个干净的徽章,我将不胜感激。如果有一种干净的方法可以让CreateDrawingImage创建一个清晰的条形码,那么它将是首选 使用iTextSharp 5.5.13.1在VS 2019 C#中开发此功能C# 使用iTextSharp将文本、图像、图片和条形码添加到PDF,c#,pdf,itext,C#,Pdf,Itext,也许我把这件事弄得更难了,但我花了很长时间把所有的东西都安排在一起,甚至出现在我的pdf上 在我的代码中,CreatePdf被称为一次性创建徽章正面,然后一次性创建徽章背面。pdf的所有对象部分都存储在数据库中,然后在此方法中循环 最初的方法只使用“graph”对象创建pdf,使用iText CreateDrawingImage生成的条形码效果非常好……除了所有的条形码都非常模糊之外。为了解决这个问题,该方法被更改为同时使用graph对象和iText图像,使用CreateImageWithBar
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();
}
}
我没有继续使用iTextSharp条形码,而是从Nugget安装了IronBarcode,并且很快就能用几行代码获得清晰、干净的条形码。生成的条形码能够导出为位图,允许我使用pdf其余部分正在使用的图形布局。问题解决了 解决方案片段:
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;
}
为什么不在文章中添加一些换行符以使其可读?您是否考虑过位图图像和pdf页面中的坐标系可能会有很大差异?位图图像API通常将原点(0,0)定位在左上角,并向下增加y坐标。另一方面,PDF的原点可以位于任何位置(通常位于左下角),并且y坐标向上递增。位图图像API通常按对象的左上角定位对象,PDF按对象的左下角定位对象。此外,您必须考虑在稍后将位图添加到PDF中时所使用的转换。因此,您必须在从添加到位图切换到添加PDF的过程中对坐标进行相当大的转换。