Added "Download PNG" option

This commit is contained in:
Przemek Wiech 2019-02-24 14:08:38 +01:00
parent 285294a3c0
commit e6be58c20b
6 changed files with 45 additions and 0 deletions

View File

@ -3,6 +3,7 @@
"version": "1.0.0",
"main": "src/index.tsx",
"dependencies": {
"canvg": "^1.5.3",
"d3": "^5.7.0",
"detect-browser": "^4.1.0",
"history": "^4.7.2",

View File

@ -1,5 +1,6 @@
import * as d3 from 'd3';
import * as React from 'react';
import canvg from 'canvg';
import {intlShape} from 'react-intl';
import {
JsonGedcomData,
@ -169,4 +170,35 @@ export class Chart extends React.PureComponent<ChartProps, {}> {
hiddenElement.download = 'topola.svg';
hiddenElement.click();
}
downloadPng() {
const canvas = document.createElement('canvas');
// Scale image for better quality.
const svg = (document.getElementById('chart') as unknown) as SVGSVGElement;
canvas.width = svg.getBBox().width * 2;
canvas.height = svg.getBBox().height * 2;
// Fill canvas with white background.
const ctx = canvas.getContext('2d')!;
const oldFill = ctx.fillStyle;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = oldFill;
canvg(canvas, this.getSvgContents(), {
ignoreDimensions: true,
ignoreClear: true,
scaleWidth: canvas.width,
scaleHeight: canvas.height,
});
const onBlob = (blob: Blob | null) => {
const hiddenElement = document.createElement('a');
hiddenElement.href = URL.createObjectURL(blob);
hiddenElement.target = '_blank';
hiddenElement.download = 'topola.png';
hiddenElement.click();
};
canvas.toBlob(onBlob, 'image/png');
}
}

View File

@ -261,4 +261,10 @@ export class ChartView extends React.Component<RouteComponentProps, State> {
this.chartRef.downloadSvg();
}
}
downloadPng() {
if (this.chartRef) {
this.chartRef.downloadPng();
}
}
}

View File

@ -48,6 +48,7 @@ if (browser && browser.name === 'ie') {
{...props}
onPrint={() => chartViewRef && chartViewRef.print()}
onDownloadSvg={() => chartViewRef && chartViewRef.downloadSvg()}
onDownloadPng={() => chartViewRef && chartViewRef.downloadPng()}
/>
)}
/>

View File

@ -24,6 +24,7 @@ interface State {
interface Props {
onPrint: () => void;
onDownloadSvg: () => void;
onDownloadPng: () => void;
}
export class TopBar extends React.Component<
@ -187,6 +188,9 @@ export class TopBar extends React.Component<
className="item"
>
<Dropdown.Menu>
<Dropdown.Item onClick={() => this.props.onDownloadPng()}>
<FormattedMessage id="menu.png_file" defaultMessage="PNG file" />
</Dropdown.Item>
<Dropdown.Item onClick={() => this.props.onDownloadSvg()}>
<FormattedMessage id="menu.svg_file" defaultMessage="SVG file" />
</Dropdown.Item>

View File

@ -3,6 +3,7 @@
"menu.load_from_file": "Otwórz plik",
"menu.print": "Drukuj",
"menu.download": "Pobierz",
"menu.png_file": "Plik PNG",
"menu.svg_file": "Plik SVG",
"menu.github": "Źródła na GitHub",
"intro.title": "Topola Genealogy",