How to Import AmCharts into a PDF with TCPDF
Export an amCharts chart as an image or SVG, then place it in a TCPDF report. Covers amCharts 3, 4, 5, PHP code, errors and alternatives.

Short answer: do not try to import the live amCharts object into TCPDF. Render the chart in the browser, export a supported representation such as PNG, JPEG or SVG, send that representation to PHP, and place it with TCPDF’s image or SVG method. First identify whether the chart uses amCharts 3, 4 or 5 because their export APIs are different.
amCharts can also create a PDF directly in documented versions. TCPDF is useful when the chart is only one part of a larger PHP-generated report containing tables, text, headers, page numbers or other server-side sections. That division is an architectural choice based on the capabilities documented by amCharts and TCPDF.
1. Choose the export path before writing code
| Question | Use amCharts export directly | Use amCharts plus TCPDF |
|---|---|---|
| What is in the final PDF? | Primarily the chart, with optional chart data and document elements. | A complete PHP report that combines the chart with other server-generated content. |
| Where is the PDF assembled? | In the browser-side chart export workflow. | In PHP with TCPDF. |
| What crosses the browser/server boundary? | The chart exporter creates the PDF. | A raster image or SVG representation of the chart. |
| What must match? | The amCharts major version and its exporter. | The amCharts exporter and the installed TCPDF API. |
amCharts 3 uses an export plugin, amCharts 4 includes exporting in the chart core, and amCharts 5 uses an Exporting plugin. Their APIs are not interchangeable. See the amCharts 3 export documentation, amCharts 4 exporting documentation, and amCharts 5 exporting documentation.
2. Check versions and hosting conditions
- Inspect the JavaScript dependencies in your page or lockfile and record the amCharts major version.
- Check whether the PHP project uses the legacy
TCPDFclass or a newer tc-lib package. The method signatures and package structure may differ. - Serve the chart page through HTTP(S). amCharts documentation warns that pages opened with
file:///can fail during export, and local or cross-origin assets can be omitted or make a canvas unusable. - Ensure images, fonts and other chart assets are available from an origin permitted by the browser’s security rules. If the chart loads an image from another host, configure CORS or export without that asset.
3. Recommended bridge: export PNG in the browser, compose the report in PHP
PNG is the simplest boundary when predictable appearance matters more than vector output. The following example shows the data flow: amCharts produces a data URL, JavaScript posts it to PHP, and PHP decodes it before passing the bytes to TCPDF.

Browser code (amCharts 4 example)
<button id="make-pdf" type="button">Create PDF</button>
<script>
document.querySelector('#make-pdf').addEventListener('click', async () => {
// amCharts 4 exporting returns a Promise for image data.
const dataUrl = await chart.exporting.getImage('png');
const response = await fetch('/report.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chart: dataUrl })
});
if (!response.ok) {
throw new Error(`PDF request failed: ${response.status}`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'report.pdf';
link.click();
URL.revokeObjectURL(url);
});
</script>
The exact exporter call depends on the amCharts major version. Keep this amCharts 4 call with an amCharts 4 chart; use the version’s own exporter for amCharts 3 or 5.
PHP and TCPDF endpoint
<?php
// report.php
require __DIR__ . '/vendor/autoload.php';
use TCPDF;
header('Content-Type: application/pdf');
$payload = json_decode(file_get_contents('php://input'), true);
$dataUrl = $payload['chart'] ?? '';
if (!is_string($dataUrl) || !preg_match('#^data:image/png;base64,#', $dataUrl)) {
http_response_code(400);
header('Content-Type: text/plain; charset=utf-8');
exit('Expected a PNG data URL.');
}
$base64 = substr($dataUrl, strlen('data:image/png;base64,'));
$png = base64_decode($base64, true);
if ($png === false || $png === '') {
http_response_code(400);
header('Content-Type: text/plain; charset=utf-8');
exit('Invalid base64 image data.');
}
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('PHP');
$pdf->SetTitle('Chart report');
$pdf->SetMargins(15, 18, 15);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 11);
$pdf->Write(8, 'Chart report');
// TCPDF accepts raw image data with the @ prefix in the legacy API.
$pdf->Image('@' . $png, 15, 32, 180, 0, 'PNG', '', '', false, 300);
$pdf->Ln(105);
$pdf->Write(8, 'Additional PHP-generated text can follow here.');
$pdf->Output('report.pdf', 'I');
Install the legacy package in a project that uses this class with composer require tecnickcom/tcpdf. If your application uses tc-lib, follow that package’s matching API instead of copying a legacy class example. The official TCPDF API reference documents Image() and ImageSVG().
4. Using SVG when vector output matters
SVG can preserve vector geometry and text-like edges at different PDF sizes. Export SVG only when the installed TCPDF renderer supports the SVG features used by your chart. Filters, external images, fonts and browser-specific effects may not reproduce identically.
<?php
$svg = file_get_contents(__DIR__ . '/chart.svg');
if ($svg === false) {
throw new RuntimeException('Chart SVG could not be read.');
}
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->ImageSVG('@' . $svg, 15, 25, 180, 0, '', '', '', 0, false);
$pdf->Output('chart-svg.pdf', 'I');
Use the installed method signature as documented for your TCPDF version. The TCPDF image methods example covers JPEG, PNG and SVG placement.
5. Version-specific amCharts guidance
amCharts 3
Load and configure the amCharts 3 export plugin. Its documentation lists PDF among supported formats and describes PDF content configuration. For a TCPDF report, request an image representation from the plugin, send it to PHP, and place it with Image(). Browser security can affect locally opened pages and images loaded from another host.
amCharts 4
Exporting is part of the chart core. The exporter supports chart-view formats including PDF and can return image data for later processing, which makes it suitable for the browser-to-PHP bridge above. Its documentation also describes PDF scale and image-dimension options.
amCharts 5
Load the Exporting plugin for image, PDF, data or print operations. amCharts 5’s PDF exporter uses pdfmake and can create a document containing a chart image, optional data and other elements. If the report belongs in PHP, export a representation and pass it to TCPDF instead. The plugin documentation warns that local files are tainted and that cross-host images may be omitted.
6. Request and payload design
- Keep the chart payload bounded. Large data URLs consume browser memory and request body space. Reject unexpectedly large bodies before decoding.
- Validate the media type. Accept only the formats your endpoint needs, such as PNG or SVG, and reject arbitrary data URLs.
- Prefer HTTPS. A chart may contain confidential values; do not post it over an unencrypted connection.
- Do not trust filenames or metadata. The server should choose the PDF filename and output format.
- Separate chart generation from report generation. If rendering is slow, queue the browser export or upload the image to a temporary, access-controlled location.
7. Common errors and fixes
| Error | Likely cause | Fix |
|---|---|---|
| Export is blank | The chart has not finished rendering. | Wait for the chart’s ready event or a known data-rendered state before requesting the image. |
| Export throws a tainted-canvas or security error | An image or font came from another origin without suitable CORS headers. | Serve the asset with CORS, host it on the same origin, or remove it from the export. |
| Export fails only when opened from disk | The page uses file:///. |
Serve the page through a local HTTP server or your normal application host. |
| TCPDF reports an invalid image | The data URL prefix was not removed, base64 is malformed, or the bytes are not the declared format. | Validate the prefix, use strict base64 decoding, and inspect the first bytes of the decoded payload. |
| SVG is clipped or missing effects | The renderer does not support a chart’s SVG features. | Try PNG for predictable output, simplify the SVG, or validate against the exact TCPDF package in deployment. |
| PHP memory limit is exceeded | A high-resolution chart and a large PDF are held in memory together. | Reduce export dimensions, process one chart at a time, and avoid retaining duplicate base64 and binary strings. |
| PDF contains the chart but not other report content | TCPDF coordinates or page breaks were not adjusted after image placement. | Track the image height, call Ln() or set the next Y position, and add pages when needed. |
8. Reliability and performance checklist
- Wait for chart data, fonts and images before exporting.
- Use a fixed export width and height when reports must be comparable.
- Choose PNG for consistent rendering; evaluate SVG only after checking the deployed renderer.
- Set server request limits high enough for the largest expected chart, but reject unbounded payloads.
- Log export failures separately from PDF failures so you can identify which layer broke.
- For repeated reports, cache the chart representation using a key based on chart data and configuration.
- Generate charts and PDFs asynchronously when a request can exceed normal HTTP timeouts.
- Do not claim a universal export quality or speed: results depend on chart complexity, assets, browser, PHP limits and the installed library versions.
9. Or skip the browser setup
ScreenshotNeo provides a website screenshot API when you need a rendered page or chart image without maintaining browser automation. One GET request returns a PNG, JPEG, WebP or PDF. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Cookie and consent banners, newsletter popups and chat widgets are removed before the shot. Bot checks, blank pages and failed loads are never billed, and response headers identify the page verdict and billing result. An MCP server lets AI agents use take_screenshot, get_page_info and capture_pdf. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
10. FAQ
Can TCPDF render an amCharts JavaScript chart directly?
No. TCPDF is a PHP PDF library; it needs exported image or SVG bytes rather than a live browser chart.
Should I use amCharts’ own PDF exporter?
Use it when the chart exporter can produce the standalone document you need. Choose TCPDF when PHP must assemble the chart with a larger report.
Is SVG always better than PNG?
No. SVG can preserve vectors, but renderer support varies. PNG is usually the safer interchange format when consistent appearance matters.
Why is there no single universal code sample for all amCharts versions?
amCharts 3, 4 and 5 use different export systems. Confirm the major version before selecting an exporter call.
Where should I troubleshoot first?
Check the browser console and network requests first, then validate the decoded image or SVG bytes, and finally inspect TCPDF placement and page coordinates.


