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