Created
February 13, 2025 11:32
-
-
Save carloswm85/f1f6e429e0b5cf15a7a378cca6cbd27e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Web.Mvc; | |
using iText.Barcodes; | |
using iText.IO.Font; | |
using iText.IO.Font.Constants; | |
using iText.IO.Image; | |
using iText.Kernel.Colors; | |
using iText.Kernel.Font; | |
using iText.Kernel.Geom; | |
using iText.Kernel.Pdf; | |
using iText.Kernel.Pdf.Xobject; | |
using iText.Layout; | |
using iText.Layout.Borders; | |
using iText.Layout.Element; | |
using iText.Layout.Properties; | |
using MiningTracker.Service; | |
using MiningTracker.Web.Controllers.Mappers.Interfaces; | |
using MiningTracker.Web.Tools; | |
namespace MiningTracker.Web.Controllers | |
{ | |
public partial class ReportController : BaseController | |
{ | |
#region Fields | |
// Services | |
private readonly IAccountService _accountService; | |
private readonly IAdminService _adminService; | |
private readonly IConfigurationService _configurationService; | |
private readonly IMiningService _miningService; | |
private readonly IOperationsService _operationsService; | |
private readonly ITrackerService _trackerService; | |
// Mappers | |
private readonly IMetarequestVmMapper _metarequestVmMapper; | |
private readonly IMineralVmMapper _mineralVmMapper; | |
private readonly IRequestVmMapper _requestVmMapper; | |
private readonly ITrackerVmMapper _trackerVmMapper; | |
#endregion Fields | |
#region Constructor | |
public ReportController( | |
// Services | |
IAccountService accountService, | |
IAdminService adminService, | |
IConfigurationService configurationService, | |
IMiningService miningService, | |
IOperationsService operationsService, | |
ITrackerService trackerService, | |
// Mappers | |
IMetarequestVmMapper metarequestVmMapper, | |
IMineralVmMapper mineralVmMapper, | |
IRequestVmMapper requestVmMapper, | |
ITrackerVmMapper trackerVmMapper | |
) | |
{ | |
// Services | |
_accountService = accountService; | |
_adminService = adminService; | |
_configurationService = configurationService; | |
_miningService = miningService; | |
_operationsService = operationsService; | |
_trackerService = trackerService; | |
// Mappers | |
_metarequestVmMapper = metarequestVmMapper; | |
_mineralVmMapper = mineralVmMapper; | |
_requestVmMapper = requestVmMapper; | |
_trackerVmMapper = trackerVmMapper; | |
} | |
#endregion Constructor | |
public virtual ActionResult TrackerbookPdfView(int id) | |
{ | |
// DOCUMENTATION | |
// https://api.itextpdf.com/iText/dotnet/9.0.0/ | |
// https://www.nuget.org/packages/itext7/9.0.0#readme-body-tab | |
// https://kb.itextpdf.com/itext/examples | |
try | |
{ | |
var request = _trackerService.GetRequestItem(id); | |
//var document = new Document(new PdfDocument(new PdfWriter("helloworld-pdf.pdf"))); | |
MemoryStream outputPath = new MemoryStream(); | |
using (PdfWriter writer = new PdfWriter(outputPath)) | |
using (PdfDocument pdf = new PdfDocument(writer)) | |
{ | |
// ================================================================================================= Page Set Up | |
// Real trackerbook size → 113 x 220 mm | |
// https://github.com/LibrePDF/OpenPDF/issues/335#issuecomment-583762850 | |
float width = 113f * 72f / 25.4f; | |
float height = 220f * 72f / 25.4f; | |
var pageSizeDimensions = new Rectangle(width, height); | |
var pageSize = new PageSize(pageSizeDimensions); | |
Document document = new Document(pdfDoc: pdf, pageSize: pageSize); | |
document.SetMargins(20, 30, 30, 20); | |
// ================================================================================================= Font Set Up | |
var customFont = false; | |
PdfFont regular; | |
PdfFont bold; | |
PdfFont medium; | |
if (customFont) | |
{ | |
// NOT WORKING | |
//string regularPath = Server.MapPath("~\\fonts\\Manrope-Regular.ttf"); | |
// FontProgramFactory.RegisterFont(regularPath, "m-regular"); | |
//regular = PdfFontFactory.CreateRegisteredFont("m-regular"); | |
string MANROPE_REGULAR = Server.MapPath("fonts/Manrope-Regular.ttf"); | |
string MANROPE_MEDIUM = Server.MapPath("fonts/Manrope-Medium.ttf"); | |
string MANROPE_BOLD = Server.MapPath("fonts/Manrope-Bold.ttf"); | |
regular = PdfFontFactory.CreateFont(MANROPE_REGULAR, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED); | |
medium = PdfFontFactory.CreateFont(MANROPE_MEDIUM, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED); | |
bold = PdfFontFactory.CreateFont(MANROPE_BOLD, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED); | |
} | |
else | |
{ | |
regular = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); | |
bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD); | |
} | |
// ================================================================================================= Cover | |
document.Add(new Paragraph("GUÍAS MINERAS") | |
.SetFont(regular) | |
.SetFontSize(14) | |
.SetTextAlignment(TextAlignment.CENTER)); | |
Table logosTable = new Table(numColumns: 2).UseAllAvailableWidth(); | |
logosTable.AddCell(new Cell().Add( | |
new Image( | |
ImageDataFactory.Create( | |
Server.MapPath("~\\Content\\images\\logos-2\\escudo-gobierno-transparente-negro.png") | |
)).SetHorizontalAlignment(HorizontalAlignment.RIGHT).SetHeight(50) | |
).SetBorder(Border.NO_BORDER)); | |
document.Add(new Image( | |
ImageDataFactory.Create( | |
Server.MapPath("~\\Content\\images\\logos-2\\isologotipo-transparente-negro.png") | |
))); | |
document.Add(new Image( | |
ImageDataFactory.Create( | |
Server.MapPath("~\\Content\\images\\logos-2\\escudo-gobierno-transparente-negro.png") | |
))); | |
document.Add(new Paragraph("Dirección Provincial de Minería") | |
.SetFontSize(16) | |
.SetTextAlignment(TextAlignment.CENTER)); | |
document.Add(new Paragraph("Ministerio de Energía y Recursos Naturales") | |
.SetFont(regular) | |
.SetFontSize(14) | |
.SetTextAlignment(TextAlignment.CENTER)); | |
document.Add(new Paragraph("Subsecretaría de Energía, Minería e Hidrocarburos") | |
.SetFontSize(12) | |
.SetTextAlignment(TextAlignment.CENTER)); | |
Table trackerbookCover = new Table(numColumns: 2).UseAllAvailableWidth(); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell("Talonario N°: ")); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell(". . . . . . . . . . . . . . . . . .")); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell("Titular: ")); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell(". . . . . . . . . . . . . . . . . .")); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell("Expte N°: ")); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell(". . . . . . . . . . . . . . . . . .")); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell("Productor minero: ")); | |
trackerbookCover.AddCell(ReportHelpers.CreateCell(". . . . . . . . . . . . . . . . . .")); | |
// ================================================================================================= Pages: 1, 2, 3 | |
int pagesCount = 3; | |
for (int i = 0; i < pagesCount; i++) | |
{ | |
document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE)); | |
document.Add(new Paragraph($"Serie E Guia Minera") | |
.SetFontSize(16)); | |
// FIELDS | |
document.Add(ReportHelpers.CreateField("Mineral", regular)); | |
document.Add(ReportHelpers.CreateField("Cantidad (Tn)", regular)); | |
document.Add(ReportHelpers.CreateField("Titular", regular)); | |
document.Add(ReportHelpers.CreateField("Expte. N°", regular)); | |
document.Add(ReportHelpers.CreateField("Expte. GDE", regular)); | |
document.Add(ReportHelpers.CreateField("Cantera/Mina", regular)); | |
document.Add(ReportHelpers.CreateField("Grado de Industrialización", regular)); | |
document.Add(ReportHelpers.CreateField("[ ] Sí [ ] No", regular)); | |
document.Add(ReportHelpers.CreateField("Destinatario", regular)); | |
document.Add(ReportHelpers.CreateField("Lugar de destino", regular)); | |
document.Add(ReportHelpers.CreateField("Uso", regular)); | |
document.Add(ReportHelpers.CreateField("País", regular)); | |
document.Add(ReportHelpers.CreateField("Fecha y hora de expedición", regular)); | |
document.Add(ReportHelpers.CreateField("Dominio vehículo", regular)); | |
document.Add(ReportHelpers.CreateField("Firma", regular)); | |
document.Add(ReportHelpers.CreateField("Aclaración", regular)); | |
// ----------------------------------------------------- Set Codes | |
var qrCodeTable = new Table(numColumns: 2, largeTable: false); | |
var qrCodeImage = ReportHelpers.GetQRCodeImage("https://www.google.com", ColorConstants.BLACK, pdf) | |
.SetHorizontalAlignment(HorizontalAlignment.RIGHT) | |
.SetHeight(100); | |
qrCodeTable.AddCell(new Cell().Add(qrCodeImage).SetBorder(Border.NO_BORDER)); | |
qrCodeTable.AddCell(ReportHelpers.CreateCell("GUÍA AUTORIZADA")); | |
qrCodeTable.AddCell(ReportHelpers.CreateCell("Ley 260/62")); | |
qrCodeTable.AddCell(ReportHelpers.CreateCell("Vencimiento")); | |
qrCodeTable.AddCell(ReportHelpers.CreateCell("30 Abril 2018")); | |
document.Add(qrCodeTable); | |
// ----------------------------------------------------- End of Tracker Ticket | |
switch (pagesCount) | |
{ | |
case 0: | |
document.Add(new Paragraph("Guía Original").SetFontSize(12)); | |
break; | |
case 1: | |
document.Add(new Paragraph("Guía Duplicado").SetFontSize(12)); | |
break; | |
case 2: | |
document.Add(new Paragraph("Guía Triplicado").SetFontSize(12)); | |
break; | |
default: | |
break; | |
} | |
if (pagesCount == 1) | |
{ | |
document.Add(new Paragraph("Guía Original").SetFontSize(12)); | |
} | |
} // for loop | |
// ================================================================================================= Close Document | |
document.Close(); | |
} | |
Console.WriteLine($"PDF created: {outputPath}"); | |
byte[] bytesStream = outputPath.ToArray(); | |
outputPath = new MemoryStream(); | |
outputPath.Write(bytesStream, 0, bytesStream.Length); | |
outputPath.Position = 0; | |
return new FileStreamResult(outputPath, "application/pdf"); | |
} | |
catch (Exception ex) | |
{ | |
string iError = LogHelper.LogError(ex, "Request", "Pdf"); | |
Debug.WriteLine(iError); | |
return null; | |
} | |
} | |
public static class ReportHelpers | |
{ | |
public static Image GetQRCodeImage(string text, Color qrColor, PdfDocument document) | |
{ | |
//Create a barcode object | |
var qrCode = new BarcodeQRCode(); | |
qrCode.SetCode(text); | |
var qrCodeObject = qrCode.CreateFormXObject(qrColor, document); | |
return new Image(qrCodeObject); | |
} | |
public static Image GetBarcodeImage(string text, Color BarCodcolor, Color BarcodTextColor, PdfDocument document) | |
{ | |
Barcode128 barcode = new Barcode128(document); | |
barcode.SetCode(text); | |
barcode.SetCodeType(Barcode128.CODE128); | |
barcode.SetBarHeight(20); | |
PdfFormXObject barcodeObject = barcode.CreateFormXObject(BarCodcolor, BarcodTextColor, document); | |
var barcodeImage = new Image(barcodeObject); | |
return barcodeImage; | |
} | |
public static Image ConvertToITextImage(System.Drawing.Image drawingImage) | |
{ | |
// Convert System.Drawing.Image to a byte array | |
using (var ms = new MemoryStream()) | |
{ | |
drawingImage.Save(ms, drawingImage.RawFormat); | |
byte[] imageBytes = ms.ToArray(); | |
var imageData = ImageDataFactory.Create(imageBytes); | |
return new Image(imageData); | |
} | |
} | |
public static Image ConvertBytesToITextImage(byte[] imageBytes) | |
{ | |
// Create iText ImageData object from the byte array | |
var imageData = ImageDataFactory.Create(imageBytes); | |
return new Image(imageData); | |
} | |
public static Cell CreateCell(string text) | |
{ | |
return new Cell().Add(new Paragraph(text)) | |
.SetBorder(Border.NO_BORDER) | |
.SetFontSize(10); | |
} | |
public static Paragraph CreateField(string text, PdfFont font, float size = 11) | |
{ | |
text = text + ": "; | |
int dotsNeeded = 70 - text.Length; | |
if (dotsNeeded > 0) | |
{ | |
text += string.Concat(Enumerable.Repeat(".", dotsNeeded)); | |
} | |
return new Paragraph(text) | |
.SetFont(font) | |
.SetFontSize(size) | |
.SetTextAlignment(TextAlignment.JUSTIFIED); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment