How can I convert HTML with CSS to PDF?
You could use the following as an example for testing:
Country Code Phone Language Population Banana Rama Foo bar Constants Empty Cells More End Germany de +49 German 82 Million JavaScript does not work. dasfd asfawerf asdfvas fwer asd fasdf asdfa sdfa sdf asdf asdf asdfa sdf asd - asdf asdfasd fasdf asdfa sdfasdf ad fasd fasd fasd fasdf asd fasdf as France fr +01 French 70 Million a asdfa sdf asdf asdf asdfasd asdf asdf asd fasd fasdfa sdf aerte fasf werwasdfa sd3e asdf adfasdfe werfa sdfas as dfasd fasd fasd fasd fasd asd fasd fasdf asdf asd fasdf asdf asd fasdf asdf as dfa sd asfdas asfd Great Britain uk +02 English 60 Million asdfasdf asdf asdfa sdf asdfasdf asd fasdf asdf asdfwr wadfa sd f ada asdf asd a sd fasd fasdf asdf asdfa sdf a asasd asdf asd fasd fas asd fasdf United States of America us +03 English 300 Million asdf asdfasd fasdfwerwfasdfasdf asdfasdfasd a dfasdf asdf asdf rt asdf asdfasd asdf asd fasd fas a dsfas fasd f a dsfa sdfasd fasd f a dsfasd asdf asdf asd fafasd fas fas
Chrome makes the following out of it with its print function:
- The page is in landscape mode ✓
- The font is changed for Country ✓
- Code is red ✓
- Phone is red ✓
- The table is striped ✓
- JavaScript is applied ✓
Create PDF With CSS Styles Using Python 3 Flask weasyprint
In this tutorial, I’ll give you an example source code of Python 3, Flask, and weasyprint to create PDF documents with CSS styles. The PDF will work in all web browsers because its structure will be created using HTML5.
pip install flask_weasyprint
code.py
import io import struct import unittest import cairo from flask import Flask, redirect, request, json, jsonify from werkzeug.test import ClientRedirectError from flask_weasyprint import make_url_fetcher, HTML, CSS, render_pdf from flask_weasyprint.test_app import app, docameent_html clast TestFlaskWeasyPrint(unittest.TestCase): def test_url_fetcher(self): # A request context is required self.astertRaises(RuntimeError, make_url_fetcher) # But only for fist creating the fetcher, not for using it. with app.test_request_context(base_url='http://example.org/bar/'): fetcher = make_url_fetcher() result = fetcher('http://example.org/bar/') astert result['string'].strip().startswith(b'') astert result['mime_type'] == 'text/html' astert result['encoding'] == 'utf-8' astert result['redirected_url'] == 'http://example.org/bar/foo/' result = fetcher('http://example.org/bar/foo/graph?data=1&labels=A') astert result['string'].strip().startswith(b'> 24 rgb = uint32 & 0xffffff astert alpha == 0xff return '#%06X' % (rgb) colors = [get_pixel(x, 320) for x in [180, 280, 380]] astert colors == app.config['GRAPH_COLORS'] astert data[:4] == b'\x00\x00\x00\x00' # Pixel (0, 0) is transparent def test_redirects(self): app = Flask(__name__) def add_redirect(old_url, new_url): app.add_url_rule( old_url, 'redirect_' + old_url, lambda: redirect(new_url)) add_redirect('/a', '/b') add_redirect('/b', '/c') add_redirect('/c', '/d') app.add_url_rule('/d', 'd', lambda: 'Ok') add_redirect('/1', '/2') add_redirect('/2', '/3') add_redirect('/3', '/1') # redirect loop with app.test_request_context(): fetcher = make_url_fetcher() result = fetcher('http://localhost/a') astert result['string'] == b'Ok' astert result['redirected_url'] == 'http://localhost/d' self.astertRaises(ClientRedirectError, fetcher, 'http://localhost/1') self.astertRaises(ValueError, fetcher, 'http://localhost/nonexistent') def test_dispatcher(self): app = Flask(__name__) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/') @app.route('/', subdomain='') @app.route('/') @app.route('/', subdomain='') def catchall(sub='', path=None): return jsonify(app=[sub, request.script_root, request.path, request.query_string.decode('utf8')]) def dummy_fetcher(url): return def astert_app(url, host, script_root, path, query_string=''): """The URL was dispatched to the app with these parameters.""" astert json.loads(dispatcher(url)['string']) == < 'app': [host, script_root, path, query_string]>def astert_dummy(url): """The URL was not dispatched, the default fetcher was used.""" astert dispatcher(url)['string'] == 'dummy ' + url # No SERVER_NAME config, default port with app.test_request_context(base_url='http://a.net/b/'): dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher) astert_app('http://a.net/b', '', '/b', '/') astert_app('http://a.net/b/', '', '/b', '/') astert_app('http://a.net/b/c/d?e', '', '/b', '/c/d', 'e') astert_app('http://a.net:80/b/c/d?e', '', '/b', '/c/d', 'e') astert_dummy('http://a.net/other/prefix') astert_dummy('http://subdomain.a.net/b/') astert_dummy('http://other.net/b/') astert_dummy('http://a.net:8888/b/') astert_dummy('https://a.net/b/') # Change the context's port number with app.test_request_context(base_url='http://a.net:8888/b/'): dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher) astert_app('http://a.net:8888/b', '', '/b', '/') astert_app('http://a.net:8888/b/', '', '/b', '/') astert_app('http://a.net:8888/b/cd?e', '', '/b', '/cd', 'e') astert_dummy('http://subdomain.a.net:8888/b/') astert_dummy('http://a.net:8888/other/prefix') astert_dummy('http://a.net/b/') astert_dummy('http://a.net:80/b/') astert_dummy('https://a.net/b/') astert_dummy('https://a.net:443/b/') astert_dummy('https://a.net:8888/b/') # Add a SERVER_NAME config app.config['SERVER_NAME'] = 'a.net' with app.test_request_context(): dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher) astert_app('http://a.net', '', '', '/') astert_app('http://a.net/', '', '', '/') astert_app('http://a.net/b/c/d?e', '', '', '/b/c/d', 'e') astert_app('http://a.net:80/b/c/d?e', '', '', '/b/c/d', 'e') astert_app('https://a.net/b/c/d?e', '', '', '/b/c/d', 'e') astert_app('https://a.net:443/b/c/d?e', '', '', '/b/c/d', 'e') astert_app('http://subdomain.a.net/b/', 'subdomain', '', '/b/') astert_dummy('http://other.net/b/') astert_dummy('http://a.net:8888/b/') # SERVER_NAME with a port number app.config['SERVER_NAME'] = 'a.net:8888' with app.test_request_context(): dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher) astert_app('http://a.net:8888', '', '', '/') astert_app('http://a.net:8888/', '', '', '/') astert_app('http://a.net:8888/b/c/d?e', '', '', '/b/c/d', 'e') astert_app('https://a.net:8888/b/c/d?e', '', '', '/b/c/d', 'e') astert_app('http://subdomain.a.net:8888/b/', 'subdomain', '', '/b/') astert_dummy('http://other.net:8888/b/') astert_dummy('http://a.net:5555/b/') astert_dummy('http://a.net/b/') def test_funky_urls(self): with app.test_request_context(base_url='http://example.net/'): fetcher = make_url_fetcher() def astert_past(url): astert fetcher(url)['string'] == u'past !'.encode('utf8') astert_past(u'http://example.net/Unïĉodé/past !') astert_past(u'http://example.net/Unïĉodé/past !'.encode('utf8')) astert_past(u'http://example.net/foo%20bar/p%61ss%C2%A0!') astert_past(b'http://example.net/foo%20bar/p%61ss%C2%A0!') if __name__ == '__main__': unittest.main()
Related posts:
- Create PDF Using Dynamic HTML5 Template in Python 3 Flask pdfkit
- Flutter Open URL inside Web Browser in Android & IOS
- jsPDF Autotable Tutorial: Draw Colorful Rounded Rectangle in a Cell of Table inside PDF Document
- PHP 7 FPDF Example: Add TrueType Fonts inside PDF Document
- PHP 7 FPDI Edit Existing PDF Document & Add Text Inside It
- PHP 7 TFPDF Add UTF-8 Fonts Inside PDF Document
- Flutter Create PDF Using Syncfusion Library
- Facebook Login Page HTML and CSS Source Code (Free Download)
- Rick and Morty AI Voice Over Using Replica
- Instagram Login Page HTML and CSS Code Download
- jsPDF Autotable Tutorial: Copy CSS Styles of a Table to Another Table
- jsPDF Autotable Tutorial: Give Different Widths to Columns & Rows of Table in PDF Document
- PHP 7 FPDF Example: Create PDF Document From Text File Using Javascript
- PHP 7 jsPDF Html2Canvas Example: Send Generated PDF as Email Attachment to Client Using JavaScript
- jsPDF Html2Canvas Project: Export Multiple Google Charts from Webpage to PDF Document in JavaScript
- jsPDF Html2Canvas Project: Export HTML With Multiple Graphs Plotted to PDF Document in JavaScript
- Angular 13 jsPDF Html2Canvas Project: Export Multiple HTML Div Content in Different PDF Pages Using TypeScript
- jsPDF-Autotable Auto Increase Width of Columns/Rows With Content
- jsPDF Encode PDF as BLOB Using Base64 Code & Download it
- jsPDF Set the Opacity of Text Color inside PDF Document
Custom CSS recipes for PDF templates
PDF Templates in ScreenSteps are created with HTML, CSS, and Javascript and then processed using the Prince PDF engine. This means you can customize how things look by adding your own CSS. This article contains CSS examples that you can use in the Custom CSS tab of the PDF Template editor in the ScreenSteps admin area to change the appearance of your PDF output.
Where should I put the CSS in these recipes?
Custom CSS is added to the Custom CSS tab of a PDF Template. Just copy and paste a recipe from this page into the Custom CSS field and click the Update button.
- Set the maximum height for images
- Change the maximum image size of the title page logo
- Target the title page
- Add an empty page between the cover page and the table of contents
- Use a single image for the title page
- Customize the «Table of Contents» text
- Resize text in styled text blocks
- Try to keep chapter articles on same page as chapter in table of contents
- Add content after the title page title
- Always put chapter title pages on the right page
- Keep chapter title on same page as article title
- Hide chapter title pages
- Adjust positioning of chapter title on page
- Right-justify the header text
- Set the maximum height for the logo in the header
- Always add a page break before a level 1 heading
- Add a page break before a foldable section
- Indent subheadings
- Justify text
- Change spacing between list items
- Turn off small caps on the title page
- Fit as many articles on a page as possible
- Insert the title of the current chapter into the header
- Remove spacing between paragraphs
- Float images to the right of text
- Targeting the footer
- Show chapter title and article title in header
Set the maximum height for images
By default images in a PDF document can be up to 4 inches tall. This CSS will change the max-height for the image to 3 inches.
Change the maximum image size of the title page logo
By default the title page logo has a top margin of 80pt and a maximum height of 100px. Here is an example that changes the top margin to 0pt and 400 pixels.