Spire.PDF is a professional PDF library applied to creating, writing, editing, handling and reading PDF files without any external dependencies. Get free and professional technical support for Spire.PDF for .NET, Java, Android, C++, Python.

Fri Nov 10, 2023 2:15 pm

I created a web API that allows you to print a PDF, in particular a boarding pass, on a Citizen CL-S521 model printer.
The labels have a size of 7.5 cm x 7.5 cm. I attach the code below.

Code: Select all
using Microsoft.AspNetCore.Mvc;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;

namespace WebPrintingService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PrintController : ControllerBase
    {
        private readonly string _printerName;
        private readonly string _labelWidth;
        private readonly string _labelHeight;

        private readonly ILogger<PrintController> _logger;

        public delegate void PrintCompletedCallback(string filePath);

        public PrintController(ILogger<PrintController> logger)
        {
            _logger = logger;

            var configuration = new ConfigurationBuilder()
               .SetBasePath(AppContext.BaseDirectory)
               .AddJsonFile("appsettings.json")
               .Build();

            _printerName = configuration["AppSettings:PrinterName"];
            _labelWidth = configuration["AppSettings:LabelWidth"];
            _labelHeight = configuration["AppSettings:LabelHeight"];

            _logger.LogInformation($"Printer Name: {_printerName}");
        }

        [HttpPost("Upload")]
        public async Task<IActionResult> UploadFile([FromForm] FileUploadModel model)
        {
            if (model?.File == null || model.File.Length == 0)
            {
                return BadRequest("Invalid file");
            }

            if (model.File.ContentType != "application/pdf")
            {
                return BadRequest("Only PDF files are allowed.");
            }

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    await model.File.CopyToAsync(memoryStream);

                    var filePath = $"{Guid.NewGuid()}.pdf";
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await PrintPdfToNetworkPrinterAsync(memoryStream, _printerName, filePath, (printedFilePath) =>
                        {
                            fileStream.Close();
                            if (System.IO.File.Exists(printedFilePath))
                            {
                                System.IO.File.Delete(printedFilePath);
                            }
                        });
                    }
                }

                return Ok("File uploaded and queued for printing.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }

        private async Task PrintPdfToNetworkPrinterAsync(MemoryStream pdfFile, string printerName, string filePath, PrintCompletedCallback callback)
        {
            PdfDocument adaptedPdfDocument = SetPrintingPreference(pdfFile, printerName);

            await Task.Run(() =>
            {
                adaptedPdfDocument.Print();
            });

            callback(filePath);
        }

        private PdfDocument SetPrintingPreference(MemoryStream pdfFile, string printerName)
        {
            //Dimension in centimeter
            //float labelWidthInCm = float.Parse(_labelWidth, CultureInfo.InvariantCulture.NumberFormat);
            //float labelHeightInCm = float.Parse(_labelHeight, CultureInfo.InvariantCulture.NumberFormat);

            //Create a PdfUnitConvertor instance
            //PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
           
            //Convert the custom size in cm to points
            //float labelWidthInPoints = unitCvtr.ConvertUnits(labelWidthInCm, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            //float labelHeightInPoints = unitCvtr.ConvertUnits(labelHeightInCm, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);

            //Convert the custom size in cm to pixel
            //float labelWidthInPx = unitCvtr.ConvertUnits(labelWidthInCm, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Pixel);
            //float labelHeightInPx = unitCvtr.ConvertUnits(labelHeightInCm, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Pixel);

            PdfDocument pdfDocument = new();

            pdfDocument.LoadFromStream(pdfFile);

            //PdfDocument adaptedPdfDocument = FitPdfToLabel(pdfDocument, labelWidthInPoints, labelHeightInPoints);

            //PaperSize paperSize = new("Custom", 220, 220);
            //paperSize.RawKind = (int)PaperKind.Custom;

            //adaptedPdfDocument.PrintSettings.PaperSize = paperSize;

            pdfDocument.PrintSettings.PrinterName = printerName;

            pdfDocument.PrintSettings.SelectSinglePageLayout(Spire.Pdf.Print.PdfSinglePageScalingMode.CustomScale, false, 100);

            //PdfViewerPreferences pdfViewerPreferences = pdfDocument.ViewerPreferences;
            //pdfViewerPreferences.CenterWindow = true;

            return pdfDocument;
        }

        //private PdfDocument FitPdfToLabel(PdfDocument pdfDocument, float labelWidth, float labelHeight)
        //{
        //    // Create a new PDF document with the specified label size
        //    PdfDocument labelPdf = new ();

        //    // Set pages margins
        //    labelPdf.PageSettings.Margins = new PdfMargins(0);

        //    // Set pages orientation
        //    labelPdf.PageSettings.Orientation = PdfPageOrientation.Portrait;

        //    // Iterate through the pages of the original PDF and copy them to the label PDF
        //    foreach (PdfPageBase originalPage in pdfDocument.Pages)
        //    {
        //        // Calculate the scaling factors for the original content
        //        //float scaleX = labelWidth / originalPage.Size.Width;
        //        //float scaleY = labelHeight / originalPage.Size.Height;

        //        // Create a new page with the desired label size
        //        PdfPageBase labelPage = labelPdf.Pages.Add(new SizeF(labelWidth, labelHeight));

        //        // Create a PdfTemplate from the original page's content
        //        PdfTemplate template = originalPage.CreateTemplate();
        //        //template.Graphics.ScaleTransform(scaleX, scaleY);

        //        // Draw the template onto the label page with the specified scale
        //        labelPage.Canvas.DrawTemplate(template, PointF.Empty);
        //    }

        //    return labelPdf;       
        //}
    }
}



However, when I print the boarding pass it ends up on two labels.
Do you have any suggestions? Thank you very much

fra_3007
 
Posts: 1
Joined: Fri Nov 10, 2023 1:14 pm

Mon Nov 13, 2023 2:51 am

Hello,

Thanks for your inquiry.
Based on your provided details, I conducted initial testing, but did not reproduce your issue. I used Spire.PDF Pack (Hot Fix) Version: 9.11.4 for testing. Could you please confirm if you are also using the same version?
If not, I would recommend testing with this version as it may have addressed the problem you encountered.
If the issue persists after testing with the recommended version, kindly provide us with your input PDF file and screenshots of the printing results for further investigation. You could attach them here or send them to us via email ([email protected]). Thanks in advance.

Sincerely,
Annika
E-iceblue support team
User avatar

Annika.Zhou
 
Posts: 1657
Joined: Wed Apr 07, 2021 2:50 am

Return to Spire.PDF