2

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());
    }
DonMax
  • 970
  • 3
  • 12
  • 47
  • You write: *the page size measurements (Page properties) that i pass is matching with the printed page.* That's great. But if the page size measurements match the measurements on the printed page, then what is the problem? Is it possible that you meant to write: *the page size measurements (Page properties) that i pass isn't matching with the printed page.* – Bruno Lowagie Apr 06 '16 at 07:52
  • ;-) I assumed that it was a typo and I went ahead providing an answer. – Bruno Lowagie Apr 06 '16 at 09:08

1 Answers1

2

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.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • I tried to add `writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);` in my code. By default the `Actual Size` option at pdf is selected now. But the left, top, bottom and right margins still does not appear correctly as per the given values. although the Label cells are rendered exactly the same size as given. Any clue?? – DonMax Apr 06 '16 at 11:09
  • As I explained: due to physical limitations of the hardware, printers often fail to write content that is added in the margins of a page. Is that the problem you describe in your comment? If so, then you should upgrade to a more professional, industrial printer to print your labels. If not, you should clarify your question. I have no clue what you mean when you say "margins does not appear correctly" as I don't know what you were expecting. – Bruno Lowagie Apr 06 '16 at 11:33
  • I was not meant the content but the margin size. When I export the pdf with label borders the left, right, top and bottom margins (PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8") are not printing according to the above mentioned size in the printed page. But all the label Height and Width (Width="48.5" Height="25.4") are coming out very well in the printed page. – DonMax Apr 06 '16 at 12:02
  • @DonMax What you see heavily depends on the printer. You can't reproduce it on every type of printer. You can't do anything about it by changing something to the PDF. There is no answer to that question. – Bruno Lowagie Apr 06 '16 at 12:30
  • 1
    For the OP, it might help to know that when you set a "margin" in iText you are only instructing iText to stay within those bounds (relative to the page size) when drawing things. However, those "margins" aren't actually written into the PDF because the PDF doesn't support them. Then when you print, you can set a different margin which tells the printer head (or whatever) how close to the edge of the paper to draw. As Bruno said, this instruction is unique to your specific printer and its capabilities. – Chris Haas Apr 06 '16 at 13:16
  • Thanks for clarifying @ChrisHaas That's what I meant. Reading the OP's question, one might assume that it's an iTextSharp-related problem, but it isn't and that's why there is no definitive answer to the question. This is a pity, because now the answer remains "unaccepted" while everything there is to say about this question has been said. – Bruno Lowagie Apr 06 '16 at 16:24