我正在尝试找到一种将TextArea的内容保存为PDF的方法。你有什么建议?
答案 0 :(得分:0)
您需要https://pdfbox.apache.org/download.cgi#20x的pdfbox-app-2.0.8.jar才能运行此代码。它将使用其中的areatext内容创建一个pdf文件。
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class JavaFXApplication5 extends Application {
@Override
public void start(Stage primaryStage) {
TextArea textarea = new TextArea();
Pane pane = new AnchorPane(textarea);
textarea.setPrefSize(100, 100);
Button btn = new Button();
btn.setText("To pdf");
btn.setTranslateX(100);
String text = textarea.getText();
pane.getChildren().add(btn);
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println(text);
PDFont font = PDType1Font.HELVETICA_BOLD ;
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
PDPageContentStream content;
try {
content = new PDPageContentStream(doc, page);
content.beginText();
content.moveTextPositionByAmount(300, 400);
content.setFont(font, 40);
content.drawString(textarea.getText());
content.endText();
content.close();
doc.addPage(page);
doc.save("example.pdf");
} catch (IOException ex) {
Logger.getLogger(JavaFXApplication5.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
StackPane root = new StackPane();
root.getChildren().addAll(pane);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Text to pdf example");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}