【问题标题】:2 Column Mailing Labels in itextsharp PDFitextsharp PDF 中的 2 列邮件标签
【发布时间】:2015-11-12 03:44:31
【问题描述】:

我需要在 itextsharp PDF 中创建 2 列邮件标签。我已经为 1 列标签创建了逻辑,并且工作正常。因为,我无法理解如何为带有 2 列的标签执行此操作。请考虑以下情况,

我需要做如下格式的逻辑

我有的代码

        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;

    }

【问题讨论】:

  • 你从哪里得到的代码?这很尴尬。你为什么使用PdfPRow。没有必要使用那个类,是吗?
  • 我从这里得到了代码github.com/wheelibin/SharpPDFLabel#readme。我从中更改了一些代码。
  • 那不是官方文档,不是吗?我只能重复我之前说过的话:你的代码中没有理由需要PdfPRow
  • 本周我重写了 SharpPDFLabel 代码,因为我需要它更加灵活(并且可以工作)。 github.com/finalcut/SharpPDFLabel 如果您愿意,我添加了指定每个标签内容的功能(或者继续创建一张相同的标签)。

标签: c# pdf itextsharp


【解决方案1】:

我真的不想重写 4 年前的其他人的代码,但一般来说,如果你想在一行中有多个表,你可以使用 PdfPTable.WriteSelectedRows() 方法或者你可以使用第二个外部表。

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

如果您想要(正如我的朋友所说)“Avery”标签的“情感”,那么第二个外桌可能对您来说就可以了。下面的代码大体上展示了这一点,但它没有详细说明定义表格和单元格的尺寸,因为您已经有了相应的代码。

我删除了PdfPRow,因为正如布鲁诺所说,几乎没有充分的理由使用它。我还建议不要传递Stream 对象,因为您需要处理诸如PositionCanReadCanWrite 和“缓冲区”之类的事情。相反,我通常建议在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);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 2010-11-14
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多