1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
public class MyHTMLEditorPane extends JEditorPane implements Printable {
/** Creates a new instance of MyHTMLEditorPane */
public MyHTMLEditorPane() {
String filePath = "C:\\Projects\\doc\\print_sample.html";
File file = new File(filePath);
URL url = null;
try {
url = file.toURL();
createDocument();
setPage(url);
setEditable(false);
}
catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "Erreur url : " + e.getMessage(), "URL error", JOptionPane.ERROR_MESSAGE);
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erreur IO : " + e.getMessage(), "IO error", JOptionPane.ERROR_MESSAGE);
}
}
// Creates the associated document
private void createDocument() {
HTMLEditorKit kit = new HTMLEditorKit();
setEditorKit(kit);
setDocument((HTMLDocument)kit.createDefaultDocument());
setContentType("text/html");
}
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex > 0) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D)g;
// Calculate the scale factor to fit the component to the page
double scaleX = pf.getImageableWidth() / getWidth();
double scaleY = pf.getImageableHeight() / getHeight();
double scale = Math.min(scaleX, scaleY); // get the minimum factor
// Move paper origin to page printing area corner
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.scale(scale, scale); // Apply the scale factor
// Draw the component
print(g2);
return Printable.PAGE_EXISTS;
}
} |
Partager