在我的项目中,我必须在pdf中打印带有所有自定义(如边框,颜色等)的JTable组件。对于这个要求,我搜索了一下,发现一个代码在pdfs中打印JTable。但是在打印之后我发现第一行和第一列的表格边框丢失了,而且我找不到在某个特定坐标处打印的方法。请查看以下具体代码: -
package com.jpmorgan.dqreport;
import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.io.FileOutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
public class JTable2Pdf extends JFrame {
private JTable table;
public JTable2Pdf() {
getContentPane().setLayout(new BorderLayout());
createTable();
}
private void createTable() {
Object[][] data = {
{"Kathy", "Smith",
"SnowboardingXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
table = new JTable(data, columnNames);
JPanel tPanel = new JPanel(new BorderLayout());
tPanel.add(table.getTableHeader(), BorderLayout.NORTH);
tPanel.add(table, BorderLayout.CENTER);
getContentPane().add(tPanel, BorderLayout.CENTER);
}
private void print() {
Document document = new Document(PageSize.A4.rotate());
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\jTable.pdf"));
document.open();
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
Graphics2D g2 = cb.createGraphics(500, 500);
Shape oldClip = g2.getClip();
g2.clipRect(10, 0, 500, 500);
table.print(g2);
g2.setClip(oldClip);
g2.dispose();
cb.restoreState();
} catch (Exception e) {
System.err.println(e.getMessage());
}
document.close();
}
public static void main(String[] args) {
JTable2Pdf frame = new JTable2Pdf();
frame.pack();
frame.setVisible(true);
frame.print();
}
}
请建议在某个特定坐标处打印整个JTable。
由于
答案 0 :(得分:6)
众所周知,JTable
难以正确渲染图像(或者我猜,打印)。请参阅this thread,了解一些大师的重要信息。
仔细查看该主题的屏幕截图,可以看出默认的Metal表在最左边没有边框。
但是,Nimbus PLAF中的表格确实如此。
答案 1 :(得分:4)
您好我通过添加如下代码解决了代码: -
cb.saveState();
PdfTemplate pdfTemplate = cb.createTemplate(table.getWidth(), table.getHeight());
Graphics2D g2 = pdfTemplate.createGraphics(table.getWidth(), table.getHeight());
/*g2.setColor(Color.BLACK);
g2.drawRect(x-2, y-2, table.getWidth()+2, table.getHeight()+2);*/
table.print(g2);
System.out.println("x="+x + "," + "y=" + y);
cb.addTemplate(pdfTemplate, x, y);
g2.dispose();
cb.restoreState();