3

我正在尝试使用 Cairo 和 RSVG 使用以下代码在 Python 中打印动态创建的 SVG(它是 Gtk 应用程序)。
它是一种特殊类型的纸张,正好是 147x205mm。如果我在 EOG 中打开 SVG,我可以毫无问题地打印它,但是使用下面的代码会使 SVG 变得太大,因此只有一部分适合纸张。
我正在寻找一种方法来告诉 RSVG/Cairo 将 SVG 缩放到打印上下文。

#in the initializer:
    self.PrintSettings = Gtk.PrintSettings()
    self.PrintSettings.set_paper_width(147, Gtk.Unit.MM)
    self.PrintSettings.set_paper_height(204, Gtk.Unit.MM)

    self.PageSetup = Gtk.PageSetup()
    pageSize = Gtk.PaperSize.new_custom("bill", "Papel de factura", 147, 205, Gtk.Unit.MM)
    self.PageSetup.set_paper_size(pageSize)
    self.PageSetup.set_top_margin(0, Gtk.Unit.MM)
    self.PageSetup.set_bottom_margin(0, Gtk.Unit.MM)
    self.PageSetup.set_left_margin(0, Gtk.Unit.MM)
    self.PageSetup.set_right_margin(0, Gtk.Unit.MM)

def on_PrintButton_clicked(self, widget): 
    self.make_bill() #generates the SVG as "./temp.svg"         

    printOperation = Gtk.PrintOperation()
    printOperation.set_n_pages(1)
    printOperation.set_print_settings(self.PrintSettings)        

    printOperation.set_default_page_setup(self.PageSetup)

    printOperation.connect("draw_page", self.print_bill)
    print printOperation.run(Gtk.PrintOperationAction.PRINT_DIALOG, self)

def print_bill(self, printOperation, printContext, pageNr):    
    pageSetup = printContext.get_page_setup()
    cairoContext = printContext.get_cairo_context()
    svg = rsvg.Handle(file = os.getcwd() + "/temp.svg")
    svg.render_cairo(cairoContext)
    return

如果它有用,我的 SVG 的开头(总是一样):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
version="1.1"
width="513.77954"
height="726.37793"
id="svg2">
<defs
 id="defs4" />
<metadata
 id="metadata7">
 <rdf:RDF>
  <cc:Work
     rdf:about="">
    <dc:format>image/svg+xml</dc:format>
    <dc:type
       rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
    <dc:title></dc:title>
  </cc:Work>
 </rdf:RDF>
</metadata>
<g
 transform="translate(0,-325.9842)"
 id="layer1">

更新
我添加了以下几行print_bill

    print printContext.get_width() # returns 416.692913386
    print printContext.get_height() # returns 581.102362205

这正好等于 SVG 的大小。我重新检查了 Inkscape,它告诉我,这是大小和 PX,但如果我在 MM 中查找值,它会显示正确的值。
也许有一个 SVG 标签来解决这个问题?

4

1 回答 1

0

I played around (a lot) with the transform parameter of the <g> element all my elements are wrapped in.
Reducing the first and forth parameter of the matrix in the transform tag allows you to size it into the required paper/drawing area.
It's also possible to move the complete drawing using the fifth and six parameter.

Example-Code:

<g
    transform="matrix(0.70,0,0,0.70,20,-190)"
    id="layer1">

I still assume (hope) there is a Cairo/Python way to solve this in a better way, but this should help.

于 2013-06-28T20:44:35.847 回答