DonMax
DonMax

Reputation: 960

Label Printing using iTextSharp

I have a logic to export avery label pdf. The logic exports the pdf with labels properly but when i print that pdf, the page size measurements (Page properties) that i pass isn't matching with the printed page.

Page Properties

Width="48.5" Height="25.4" HorizontalGapWidth="0" VerticalGapHeight="0" PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8" PageSize="A4" LabelsPerRow="4" LabelRowsPerPage="10"

The above property values are converted equivalent to point values first before applied.

Convert to point

    private float mmToPoint(double mm)
    {
        return (float)((mm / 25.4) * 72);
    }

Logic

    public Stream SecLabelType(LabelProp _label)
    {
        List<LabelModelClass> Model = new List<LabelModelClass>();
        Model = RetModel(_label);
        bool IncludeLabelBorders = false;
        FontFactory.RegisterDirectories();
        Rectangle pageSize;
        switch (_label.PageSize)
        {
            case "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();
        //var ItemNoArr = Model.Select(ds => ds.ItemNo).ToArray();
        //string Header = Model.Select(ds => ds.Header).FirstOrDefault();
        int cnt = 0;
        bool b = false;
        int iAddRows = 1;
        for (int iRow = 0; iRow < ((Model.Count() / _label.LabelsPerRow) + iAddRows); iRow++)
        {
            var rowCells = new List<PdfPCell>();
            for (int iCol = 1; iCol <= numOfCols; iCol++)
            {
                if (Model.Count() > cnt)
                {
                    if (iCol % 2 > 0)
                    {
                        var cellContent = new Phrase();
                        if (((iRow + 1) >= _label.StartRow && (iCol) >= (_label.StartColumn + (_label.StartColumn - 1))) || b)
                        {
                            b = true;

                            try
                            {
                                var StrArr = _label.SpineLblFormat.Split('|');

                                foreach (var x in StrArr)
                                {
                                    string Value = "";
                                    if (x.Contains(","))
                                    {
                                        var StrCommaArr = x.Split(',');
                                        foreach (var y in StrCommaArr)
                                        {
                                            if (y != "")
                                            {

                                                Value = ChunckText(cnt, Model, y, Value);

                                            }
                                        }
                                        if (Value != null && Value.Replace(" ", "") != "")
                                        {
                                            cellContent.Add(new Paragraph(Value));
                                            cellContent.Add(new Paragraph("\n"));
                                        }
                                    }
                                    else
                                    {
                                        Value = ChunckText(cnt, Model, x, Value);
                                        if (Value != null && Value.Replace(" ", "") != "")
                                        {
                                            cellContent.Add(new Paragraph(Value));
                                            cellContent.Add(new Paragraph("\n"));
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                var fontHeader1 = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 6, 0);
                                cellContent.Add(new Chunk("NA", fontHeader1));
                            }
                            cnt += 1;
                        }
                        else
                            iAddRows += 1;
                        var cell = new PdfPCell(cellContent);
                        cell.FixedHeight = _label.Height;
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        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()));
            _label.LabelRowsPerPage = _label.LabelRowsPerPage == null ? 0 : _label.LabelRowsPerPage;
            if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
            {
                tbl.Rows.Add(CreateGapRow(numOfCols, _label));
            }

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

    }

private PdfPRow CreateGapRow(int numOfCols, LabelProp _label)
    {
        var cells = new List<PdfPCell>();

        for (int i = 0; i < numOfCols; i++)
        {
            var cell = new PdfPCell();
            cell.FixedHeight = _label.VerticalGapHeight;
            cell.Border = Rectangle.NO_BORDER;
            cells.Add(cell);
        }
        return new PdfPRow(cells.ToArray());
    }

Upvotes: 2

Views: 2419

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

A PDF document may have very accurate measurements, but then those measurements get screwed up because the page is scaled during the printing process. That is a common problem: different printers will use different scaling factors with different results when you print the document using different printers.

How to avoid this?

In the print dialog of Adobe Reader, you can choose how the printer should behave:

enter image description here

By default, the printer will try to "Fit" the content on the page, but as not every printer can physically use the full page size (due to hardware limitations), there's a high chance the printer will scale the page down if you use "Fit".

It's better to choose the option "Actual size". The downside of using this option is that some content may get lost because it's too close to the border of the page in an area that physically can't be reached by the printer, but the advantage is that the measurements will be preserved.

You can set this option programmatically in your document by telling the document it shouldn't scale:

writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);

See How to set initial view properties? for more info about viewer preferences.

Upvotes: 2

Related Questions