迭代中的2个列邮件标签PDF

时间:2015-08-19 02:02:55

标签: c# pdf itextsharp

我需要在itextsharp PDF中创建2个列邮件标签。我已经为1列标签创建了逻辑,它工作正常。因为,我无法理解如何为2列标签做到这一点。 Pl考虑以下情况,

我需要按照以下格式执行逻辑

enter image description here

我有的代码

        public Stream CreatePDF(Label _label)
    {
        FontFactory.RegisterDirectories();
        Rectangle pageSize;
        switch (_label.PageSize)
        {
            case Enums.PageSize.A4:
                pageSize = iTextSharp.text.PageSize.A4;
                break;
            default:
                pageSize = iTextSharp.text.PageSize.A4;
                break;
        }

        var doc = new Document(pageSize,
                               _label.PageMarginLeft,
                               _label.PageMarginRight,
                               _label.PageMarginTop,
                               _label.PageMarginBottom);

        var output = new MemoryStream();

        var writer = PdfWriter.GetInstance(doc, output);

        writer.CloseStream = false;
        doc.Open();
        var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
        var tbl = new PdfPTable(numOfCols);
        var colWidths = new List<float>();
        for (int i = 1; i <= numOfCols; i++)
        {
            if (i % 2 > 0)
            {
                colWidths.Add(_label.Width);
            }
            else
            {
                colWidths.Add(_label.HorizontalGapWidth);
            }
        }

        var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
        var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
        var size = new iTextSharp.text.Rectangle(w, h);
        tbl.SetWidthPercentage(colWidths.ToArray(), size);
        var val = System.IO.File.ReadLines("C:\\Users\\lenovo\\Desktop\\test stock\\testing3.txt").ToArray();
        int cnt = 0;
        for (int iRow = 0; iRow < ((val.Count() / _label.LabelsPerRow) + 1); iRow++)
        {

            var rowCells = new List<PdfPCell>();
            for (int iCol = 1; iCol <= numOfCols; iCol++)
            {
                if (val.Count() > cnt)
                {
                    if (iCol % 2 > 0)
                    {
                        var cellContent = new Phrase();
                        if (val[cnt] != "")
                        {
                            var fontHeader = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 12, 0);
                            cellContent.Add(new Chunk("Default Header\n\n", fontHeader));
                            Code39BarcodeDraw barcode39 = BarcodeDrawFactory.Code39WithoutChecksum;
                            System.Drawing.Image img = barcode39.Draw(val[cnt], 25);
                            var pdfImg = iTextSharp.text.Image.GetInstance(ReadImage(img));
                            var width = pdfImg.PlainWidth;
                            if (width > colWidths.ToArray()[0])
                                pdfImg.ScaleAbsoluteWidth(colWidths.ToArray()[0] - 5);
                            cellContent.Add(new Chunk(pdfImg, 0, 0, true));
                            var font = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 12, 0);
                            cellContent.Add(new Chunk("\n\n" + val[cnt], font));
                        }
                        cnt += 1;
                        var cell = new PdfPCell(cellContent);
                        cell.FixedHeight = _label.Height;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;
                        rowCells.Add(cell);
                    }
                    else
                    {
                        var gapCell = new PdfPCell();
                        gapCell.FixedHeight = _label.Height;
                        gapCell.Border = Rectangle.NO_BORDER;
                        rowCells.Add(gapCell);
                    }
                }
                else
                {
                    var gapCell = new PdfPCell();
                    gapCell.FixedHeight = _label.Height;
                    gapCell.Border = Rectangle.NO_BORDER;
                    rowCells.Add(gapCell);
                }
            }
            tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
            if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
            {
                tbl.Rows.Add(CreateGapRow(numOfCols));
            }

        }
        doc.Add(tbl);
        doc.Close();
        output.Position = 0;
        return output;

    }

1 个答案:

答案 0 :(得分:0)

我真的不想在4年前重新编写别人的代码,但总的来说,如果你想要连续使用多个表,你可以使用PdfPTable.WriteSelectedRows()方法或您可以使用第二个外表。

PdfPTable.WriteSelectedRows()非常强大,但完全由你来计算。如果您确实需要创建与预成型贴纸完美对齐的Avery标签,那么这可能是您可以保证这些东西的唯一途径。

如果你想(正如我的朋友所说)&#34;&#34; Avery标签然后第二个外表可能对你很好。下面的代码显示了这一点,但它并没有详细说明定义表格和单元格尺寸,因为你已经有了代码。

我删除了PdfPRow,因为正如布鲁诺所说的那样,几乎从来没有一个充分的理由使用它。我还建议不要传递Stream个对象,因为您需要处理PositionCanReadCanWrite和&#34;缓冲区&#34;等内容。相反,我通常建议在Stream上进行操作,然后抓取最后可以传递的字节。其余的代码评论很多,但如果您有任何问题,请告诉我。

//Number of labels across
var labelsAcross = 2;

//Total number of labels that you need.
//This variable could come from a .Count() or you could
//remove it and customize the for loop below
var labelCount = 7;

//We're going to dump our PDF into this when done
Byte[] bytes;

//Standard iTextSharp setup here, nothing special
using (var ms = new MemoryStream()) {

    //Change the margins if you want to
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, ms)) {
            doc.Open();

            //Create a master outer table to hold everything
            var masterTable = new PdfPTable(labelsAcross);

            //We don't want borders on the master table
            //The DefaultCell is also where you can adjust
            //padding between labels themselves
            masterTable.DefaultCell.BorderWidth = 0;

            //Create a bunch of labels
            for (var i = 1; i <= labelCount; i++) {

                var t = new PdfPTable(2);
                t.AddCell("This is my left cell");
                t.AddCell("This is my right cell");

                masterTable.AddCell(t);
            }

            //Just in case we don't have enough cells
            //tell the master table to "fill in the blanks"
            masterTable.CompleteRow();

            //Add the master table to the document
            doc.Add(masterTable);
            doc.Close();
        }
    }

    //Right before closing out our stream grab the underlying byte array
    bytes = ms.ToArray();
}

//For demo purposes, write the bytes to the desktop
System.IO.File.WriteAllBytes(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"), bytes);