我想创建一个将在 Swing 应用程序中打印的 HTML 小型预览。基本上,它会以 PageFormat 类的大小(即可打印页面的大小)显示页面,但显示页面大小的 1/4 或更小。
到目前为止,我已尝试以下操作:
//Create components
JDialog frame = new JDialog(new JFrame("Test"), "Test", true);
JPanel panel = new JPanel(){
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.scale(0.5,0.5);
super.paintComponent(g2);
}};
PageFormat pf = new PageFormat();
Dimension dimension = new Dimension();
dimension.setSize(pf.getImageableWidth(), pf.getImageableHeight());
panel.setPreferredSize(dimension);
panel.add(new JEditorPane("text/html", "<i>Testing, testing, one two three</i>"));
//Finalize everything
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
不幸的是,这会创建一个全页面大小的 JPanel,但会将 JEditorPane 缩放到屏幕的左上四分之一,因为 JPanel 的大小似乎也没有缩放。另外,如果单击 JEditorPane,它会以全尺寸显示。如何才能达到我想要的效果?
此外,这不必是可编辑的 HTML 页面,因此如果有一些不涉及直接显示 HTML 的巧妙解决方案,我对此持开放态度。
最佳答案
http://java-sl.com/JEditorPanePrinter.html您可以使用代码来查看预览是如何实现的。
或者你可以定义一个BufferedImage
传递所需的宽度/高度>使用图像的getGraphics()
并应用你需要的AffineTransform
(缩放在最简单的情况下)。然后只需调用 yourJEditorPane.paint(g)
,其中 g 是图像的Graphics
。
关于java - 创建打印 HTML 页面的预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860906/