To embed custom fonts in PDFs using Spatie Browsershot without disabling web security, you can try the following steps:
-
Ensure Correct Font Path: Make sure the font path is accessible to the Browsershot process. Since Browsershot uses headless Chrome, it needs to access the font file directly. Use an absolute path to the font file in your CSS.
-
Serve Fonts via HTTP: Instead of using
public_path(), serve the font files via HTTP. This can be done by placing the font files in thepublicdirectory and using theasset()helper to generate the URL. -
Use a Local Web Server: Ensure that your local development server is running and accessible. Browsershot needs to fetch resources over HTTP, so the server must be running.
-
Check Font MIME Type: Ensure that the server is serving the font files with the correct MIME type. You can add the following to your
.htaccessfile if you're using Apache:AddType application/font-woff2 .woff2 AddType application/font-woff .woff AddType application/vnd.ms-fontobject .eot AddType font/ttf .ttf AddType font/otf .otf -
Update CSS: Modify your CSS to use the
asset()helper for the font URL:<style> @font-face { font-family: 'NotoNastaliqUrdu-Regular'; src: url("{{ asset('admin_assets/assets/urdu/NotoNastaliqUrdu.ttf') }}") format("truetype"); } .urdu-font { font-family: "NotoNastaliqUrdu-Regular"; font-optical-sizing: auto; font-weight: 500; font-style: normal; } body { font-family: 'NotoNastaliqUrdu-Regular'; } </style> -
Ensure Network Access: Make sure that your local server is accessible from the environment where Browsershot is running. If you're running this in a Docker container or a VM, ensure that the network settings allow access to the local server.
-
Debugging: Use the
->save()method to save the HTML output to a file and open it in a regular browser to ensure that the font is loading correctly. This can help you identify if the issue is with the font loading or with Browsershot.
By following these steps, you should be able to embed custom fonts in your PDFs securely without disabling web security. If the issue persists, consider checking the network requests in the headless Chrome instance to ensure that the font file is being requested and loaded correctly.