angularpdfhtml2pdf

Angular convert html to pdf with css


I need to convert html to pdf with css, I used windows.print() but it doesn't include css styles

Html:

<button type="submit" (click)="generatePDFDescription()">
Generate Pdf
</button>
<div id="print-section">
...
</div>

Component classe:

@Component({
  selector: 'app-generate-pdf-description',
  templateUrl: './generate-pdf-description.component.html',
  styleUrls: ['./generate-pdf-description.component.scss']
})
export class GeneratePdfDescriptionComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  generatePDFDescription(): void {
    const element: Element = document.getElementById('print-section');
    let myWindows = window.open('', 'PRINT', 'height=400,with=600');
    myWindows.document.write("<!DOCTYPE html><html><head><meta charset='utf-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'>"+
    + "<meta name='viewport' content='width=device-width, initial-scale=1'>"
    + "<link rel='stylesheet' type='text/css' media='screen' href='./generate-pdf-description.component.scss'>");
    myWindows.document.write('</head><body>');
    myWindows.document.write(element.innerHTML);
    myWindows.document.write('</body></html>');
    myWindows.document.close();
    myWindows.focus();
    myWindows.print();
  }

}

Result:

enter image description here

Expected result:

enter image description here


Solution

  • I fixed this issue by doing two things:

    1. Adding minify css:

    enter image description here

    You can use this web site CSS Formatter to Minifiy your css.

    1. I solved the image problem by adding the base url:

    enter image description here