iobio / oncogene

Cancer tailored version of gene.iobio
2 stars 1 forks source link

Export viz as high quality PDFs #204

Open stefinfection opened 3 years ago

chmille4 commented 3 years ago

Just fyi, exporting to PDF is really tough and requires e.g. a headless browser or something that can convert HTML to pdf.

An alternative is to output to SVG, which is vector just like PDF and can be imported into adobe illustrator to edit as well. I just did this in Mosaic, so I have this code handy. I'll paste it here just in case it's useful

function toSvgImage(svg) {
 // svg here is the svgnode element e.g. document.getElementById(svgId)
  const xmlns = 'http://www.w3.org/2000/xmlns/';
  const xlinkns = 'http://www.w3.org/1999/xlink';
  const svgns = 'http://www.w3.org/2000/svg';
  svg = svg.cloneNode(true);
  const fragment = `${window.location.href}#`;
  const walker = document.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
  while (walker.nextNode()) {
    // eslint-disable-next-line
    for (const attr of walker.currentNode.attributes) {
      if (attr.value.includes(fragment)) {
        attr.value = attr.value.replace(fragment, '#');
      }
    }
  }
  svg.setAttributeNS(xmlns, 'xmlns', svgns);
  svg.setAttributeNS(xmlns, 'xmlns:xlink', xlinkns);
  const serializer = new window.XMLSerializer();
  const string = serializer.serializeToString(svg);
  return new Blob([string], { type: 'image/svg+xml' });
}
function downloadFile(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0);
  }
}
stefinfection commented 3 years ago

Thanks a bunch @chmille4