【发布时间】:2019-10-01 17:58:40
【问题描述】:
我在一个项目中工作,其中产品已使用 ProductCode 注册,如果用户生成单个产品的 2 个或多个条形码,则它会生成一个 pdf,每行只有 1 个条形码,我想让它出现单页
Document doc = new Document(new iTextSharp.text.Rectangle(25, 11), 5, 8, 1, 1);
int count = int.Parse(metroTextBox11.Text);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/codes.pdf", FileMode.Create));
doc.Open();
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Price");
dt.Columns.Add("Des");
for (int i = 0; i < count; i++)
{
DataRow row = dt.NewRow();
row["ID"] = barcode;
row["Price"] = price;
row["Des"] = description;
dt.Rows.Add(row);
}
System.Drawing.Image img1 = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i != 0)
doc.NewPage();
PdfContentByte cb1 = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_BOLDITALIC, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb1.SetFontAndSize(bf, 2.0f);
cb1.BeginText();
cb1.SetTextMatrix(1.2f, 8.5f);
cb1.ShowText("Aaraiz");
cb1.EndText();
PdfContentByte cb2 = writer.DirectContent;
BaseFont bf1 = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb2.SetFontAndSize(bf1, 1.0f);
cb2.BeginText();
cb2.SetTextMatrix(1.2f, 7.0f);
cb2.ShowText("Description: "+dt.Rows[i]["Price"].ToString());
cb2.EndText();
PdfContentByte cb = writer.DirectContentUnder;
Barcode128 bc = new Barcode128();
bc.TextAlignment = Element.ALIGN_CENTER;
bc.Font = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
bc.Code = dt.Rows[i]["ID"].ToString();
bc.AltText = "Code: " + dt.Rows[i]["ID"].ToString() + " Price: " + dt.Rows[i]["Price"].ToString();
bc.StartStopText = false;
bc.CodeType = iTextSharp.text.pdf.Barcode128.EAN13;
bc.Extended = true;
iTextSharp.text.Image img = bc.CreateImageWithBarcode(cb, iTextSharp.text.BaseColor.BLACK, iTextSharp.text.BaseColor.BLACK);
cb.SetTextMatrix(1.5f, 3.0f);
img.ScaleToFit(60, 5);
img.SetAbsolutePosition(1.5f, 1);
cb.AddImage(img);
}
doc.Close();
System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/codes.pdf");
}
catch(Exception error)
{
MessageBox.Show(error.ToString());
}
finally
{
doc.Close();
}
【问题讨论】:
-
除了第一个迭代之外,您不是在每次迭代中都创建新页面吗?
if (i != 0) doc.NewPage(); -
如果我删除这块代码,它会与每个条码重叠