Export SVG elements to PDF?

后端 未结 4 1691
时光说笑
时光说笑 2021-02-05 22:56

I have a visualization generated by d3 (a javascript visualization library similar to Protovis or Raphael, which draws stuff using SVG elements). The vis is interactive, so the

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 23:51

    I did not try d3, but I achieved the effect you are looking for like this in Python3.6:

    # Pdf library
    from reportlab.pdfgen import canvas
    from reportlab.graphics import renderPDF, renderPM
    
    # Svg library
    import svgwrite
    
    # Svg to reportlab
    from svglib.svglib import svg2rlg, SvgRenderer
    
    # Xml parser
    from lxml import etree
    
    # Create the svg
    dwg = svgwrite.Drawing('test.svg', profile='tiny')
    dwg.add(dwg.line((0, 0), (10, 10), stroke=svgwrite.rgb(10, 10, 16, '%')))
    dwg.add(dwg.text('Test', insert=(0, 0.2)))
    
    # Create canvas for pdf
    c = canvas.Canvas("output.pdf")
    
    # Parse the xml of the svg
    parser = etree.XMLParser(remove_comments=True, recover=True)
    root = etree.fromstring(dwg.tostring())
    
    # Render the svg itself
    svgRenderer = SvgRenderer()
    drawing = svgRenderer.render(root)
    
    # Now render the drawing in the pdf
    renderPDF.draw(drawing , c, 10, 10)
    
    # End page and save pdf file
    c.showPage()
    c.save()
    
    # Or render to a seperate png
    renderPM.drawToFile(drawing, "file.png", fmt="PNG")
    

    Reportlab is an open source pdf library and svglib is a library that is able to convert svg's to reportlab Drawings. Rendering svg's directly from the xml is not supported out of the box, that is why I use the SvgRenderer.

提交回复
热议问题