androidcssitexthtml2pdf

Android Itext HTML to PDF CSS on SVG work only in inline


Hi I try to use itext library (html2pdf) to convert my html into a PDF. Almost everything is fine except for SVG style.

This is the part of my html that doesn't work :


<style>
  .my-svg{
      width: 3.3mm;
      height: 3.3mm;
      margin-right: 0.4mm;
      fill: red;
  }
</style>

<svg class="my-svg" width="90.507" height="90.671" viewBox="0 0 23.947 23.99" xmlns="http://www.w3.org/2000/svg">
  <path class="darkable" d="PATH" style="stroke-width:.264583;fill-opacity:1" transform="translate(-66.675 -125.148)"/>
</svg>

I tried to apply the style inline and it worked BUT for internal reasons (HTML is generated dynamically and I can't set style in inline, this criteria is not questionable btw) I need it to be under style tag.

If you have any idea why and how to fix that I would glad to read you !

PS : this is how I convert my html


val dir = createPDFReportDirectory()
val pdfFile = File(dir, "$name.pdf").apply { createNewFile() }
val pdfWriter = PdfWriter("$dir/$name.pdf")
val pdfDocument = com.itextpdf.kernel.pdf.PdfDocument(pdfWriter)

val inputStream = ByteArrayInputStream(html.toByteArray())
HtmlConverter.convertToPdf(inputStream, pdfDocument)

Solution

  • I finally found a way to do what I want. Simply wrap my svg tag in a div one.

    see under :

    <style>
        .phone-svg{
            width: 3.3mm;
            height: 3.3mm;
            margin-right: 0.4mm;
        }
    </style>
    
    <div class="darkable phone-svg">
        <svg width="100%" height="100%" viewBox="0 0 23.947 23.99" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
             <path d="PATH" style="stroke-width:.264583;fill-opacity:1" transform="translate(-66.675 -125.148)"/>
         </svg>
    </div>
    

    The CSS doesn't want to apply on SVG so I simply apply it on a a div wrapping it. I hope my answer will help someone !