'How to justify on both sides text into a DIV in HTML5 for being rendered into a PDF by using DinkToPDF
Recently I started using DinkToPdf library to convert a html in an asp.net core 6 project to a PDF file. I started by creating a Proof of Concept cshtml that will be rendered as string to finally produce a PDF by using the library. Below is my cshtml:
@using SicotX.Services.GestionDocumental.Views.Models
@*
Plantilla de Prueba
*@
@model List<Employee>
@{
Layout = "_LayoutTemplate";
}
<style>
.negrita {
font-weight: bold;
}
.subtitle {
font-family: "Arial Narrow", Arial, sans-serif;
font-size: 0.9rem;
}
.content {
/* display: flex; */
background-color: gray;
}
.content div {
text-align: justify;
white-space: normal;
}
</style>
<section class="title">
<div class="center"><h3>RESOLUCION No. 00222</h3></div>
<div class="center"><h3>del 08 de Febrero de 2015</h3></div>
<br/>
</section>
<section class="subtitle">
<h4 class="center">POR MEDIO DE LA CUAL SE RESUELVE UNA CONTRAVENCION A LAS</h4>
<h4 class="center">NORMAS DEL CODIGO NACIONAL DE TRANSITO Y SE </h4>
<h4 class="center">SUSPENDE LA LICENCIA DE CONDUCCION AL CONTRAVENTOR</h4>
</section>
<section class="content">
<br/>
<div>
EL SUSCRITO ASESOR JURIDICO DE EL INSTITUTO DE TRANSITO Y TRANSPORTE DEL XXXX - DE XXXXXXXX - S.O., en uso de sus facultades legales y en especial las conferidas en la Ley 769 de 2002 Código Nacional de Tránsito Terrestre y en las conferidas mediante resolución No. 1610 de julio 10 de 2013 y,
</div>
<br/>
<div class="center negrita">
C O N S I D E R A N D O
</div>
<br/>
<div>
Que fue impuesta la orden de comparendo No. <span class="negrita">99999999000001111223</span> de fecha <span class="negrita">02 de Febrero de 2015</span>, a <span class="negrita">ALBERTO YESID CUERVO identificado(a) con C.C.NO. 11,111,111 expedida en Bogota, Distrito Capital</span>, conductor del vehículo de placas <span class="negrita">XYZ000</span>, por presunta contravención a las normas de tránsito consistente en Conducir bajo el influjo del alcohol o bajo los efectos de sustancias psicoactivas.
</div>
<br/>
<div>Que <b>ALBERTO YESID CUERVO</b>, no asistió a la audiencia pública a fin de rendir descargos y hacer uso del derecho de defensa o asistió sin controvertir la imposición de la infracción.</div>
<br/>
<div>Que el despacho avocó el conocimiento mediante auto de fecha 02 de Febrero de 2015.</div>
<br/>
<div>Que en virtud de lo preceptuado por el artículo 152 de la ley 769 de 2002, el cual fue modificado por el artículo 25 de la Ley 1383 de 2010, que a su vez fue modificado por el artículo 1 de la ley 1548 de 2012 y esta fue modificada por el artículo 5 de la ley 1696 de 2013, que indica: "Si hecha la prueba, se establece que el conductor se encuentra en alguno de los siguientes grados de alcoholemia, incurrirá en las sanciones respectivas, según el nivel de reincidencia…"</div>
<br/>
<div>El procedimiento al cual se pone fin mediante el presente acto administrativo, ha sido desarrollado con la observancia del debido proceso el derecho de defensa previsto en el artículo 29 de la Constitución Política de Colombia, a fin de garantizar los derechos de quienes se encuentran involucrados en toda clase de actuaciones administrativas. Así mismo, con el respeto al postulado de la buena fe, previsto en normas constitucionales y legales. * Acta de Audiencia Pública No. 2013APNP005409 de fecha 08 de Febrero de 2015, </div>
<br/>
<div>Queda plenamente establecido de acuerdo a la prueba tomada por la autoridad competente, que el posible infractor ha conducido bajo el influjo del alcohol o bajo los efectos de sustancias psicoactivas, lo cual ratifica el ticket del alcohol sensor tomado por personal autorizado o informe médico legal suscrito por un profesional de la medicina.</div>
<br/>
...
</section>
The before template produces the following PDF:
It looks fine, I did this:
.content div {
text-align: justify;
white-space: normal;
}
however text is not full justified on the right side as I marked with a red marker. Trying to justify the text, I used display: flex into .content, and this is the result:
For some strange reason, bold span text is overlapping the next non bolded text, on other parts the text is cut on the right side and removed the centered bolded text aligning it to the left.
I really need to solve this, I researched in many blogs and sites with no success. Below is the controller with the configurations used for the DinkToPdf:
public PdfGeneratorController(
IViewRenderingService viewRenderingService,
IConverter converter,
ILogger<PdfGeneratorController> logger
)
{
_viewRenderingService = viewRenderingService;
_converter = converter;
_logger = logger;
}
public IActionResult CreatePDF()
{
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.Letter,
Margins = new MarginSettings { Top = 20, Bottom = 20, Left = 20, Right = 20 },
DocumentTitle = "PDF Report",
Out = @"Employee_Report.pdf"
};
System.IO.File.Delete("Employee_Report.pdf");
var model = DataStorage.GetAllEmployees();
var viewString = "";
try
{
viewString = _viewRenderingService.RenderPartialView(this, "Areas/Templates/SubAreas/ProcesoContravencional/Views/Index1.cshtml", model);
}
catch (Exception e)
{
}
var templatefiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.html", SearchOption.AllDirectories)
.Where(f => f.Contains("HeaderTemplate") || f.Contains("FooterTemplate")).ToList();
string headerTemplate = templatefiles.Where(f => f.Contains("HeaderTemplate")).SingleOrDefault();
string footerTemplate = templatefiles.Where(f => f.Contains("FooterTemplate")).SingleOrDefault();
var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent = viewString,
WebSettings = { DefaultEncoding = "utf-8" }, //, UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
HeaderSettings = { Line = true, HtmUrl = headerTemplate }, //@"bin\Debug\net6.0\Views\Shared\Templates\HeaderTemplate.html" },
FooterSettings = { Line = true, HtmUrl = footerTemplate } //@"bin\Debug\net6.0\Views\Shared\Templates\FooterTemplate.html" }
};
var pdf = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings }
};
_converter.PhaseChanged += Converter_PhaseChanged;
_converter.ProgressChanged += Converter_ProgressChanged;
_converter.Error += _converter_Error;
_converter.Convert(pdf);
return Ok("Successfully created PDF document.");
}
private void _converter_Error(object sender, DinkToPdf.EventDefinitions.ErrorArgs e)
{
Console.WriteLine("Error {0}", e.Message);
}
private static void Converter_ProgressChanged(object sender, DinkToPdf.EventDefinitions.ProgressChangedArgs e)
{
Console.WriteLine("Progress changed {0}", e.Description);
}
private static void Converter_PhaseChanged(object sender, DinkToPdf.EventDefinitions.PhaseChangedArgs e)
{
Console.WriteLine("Phase changed {0} - {1}", e.CurrentPhase, e.Description);
}
}
I appreciate your help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


