JavaFX HTMLEditor chèn hình ảnh base64 tại vị trí xác định tách js
1) JavaScript lưu trong thư mục “resources\js\insertHtmlAfterCursor.js”;
(function(html) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(),
node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
else if (document.selection &&
document.selection.type != "Control") {
document.selection.createRange().pasteHTML(html);
}
})("%s");
CustomHTMLEditor
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.geometry.Orientation;
import javafx.scene.control.Button;
import javafx.scene.control.Separator;
import javafx.scene.control.ToolBar;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
public class CustomHTMLEditor extends HTMLEditor {
public static final String TOP_TOOLBAR = ".top-toolbar";
public static final String BOTTOM_TOOLBAR = ".bottom-toolbar";
public static final String WEB_VIEW = ".web-view";
private static final String IMPORT_BUTTON_GENERAL = "embed.png";
private final WebView mWebView;
private final ToolBar mTopToolBar;
private final ToolBar mBottomToolBar;
private Button mImportFileButton;
public CustomHTMLEditor() {
mWebView = (WebView) this.lookup(WEB_VIEW);
mTopToolBar = (ToolBar) this.lookup(TOP_TOOLBAR);
mBottomToolBar = (ToolBar) this.lookup(BOTTOM_TOOLBAR);
GridPane.setVgrow(mWebView, Priority.ALWAYS);
createCustomButtons();
this.setHtmlText("<html />");
}
/**
* Inserts HTML data after the current cursor. If anything is selected, they
* get replaced with new HTML data.
*
* @param html HTML data to insert.
*/
public void insertHtmlAfterCursor(String html) {
//replace invalid chars
html = html.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\r", "\\r")
.replace("\n", "\\n");
String filePath = "/js/insertHtmlAfterCursor.js";
// Đọc nội dung của tệp JavaScript
String script = String.format(readScriptFile(filePath), html);
mWebView.getEngine().executeScript(script);
}
// Ph??ng th?c ?? ??c n?i dung c?a t?p JavaScript ??a ch? t??ng ??i
private String readScriptFile(String filePath) {
try {
StringBuilder contentBuilder = new StringBuilder();
InputStream is = getClass().getResourceAsStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
contentBuilder.append(line).append("\n");
}
return contentBuilder.toString();
} catch (IOException e) {
return null;
}
}
/**
* Creates Custom ToolBar buttons and other controls
*/
private void createCustomButtons() {
//add embed file button
// ImageView graphic = new ImageView(new Image(
// getClass().getResourceAsStream(IMPORT_BUTTON_GENERAL)));
// mImportFileButton = new Button("Import File", graphic);
mImportFileButton = new Button("Import File");
mImportFileButton.setTooltip(new Tooltip("Import File"));
mImportFileButton.setOnAction((event) -> onImportFileButtonAction());
//add to top toolbar
mTopToolBar.getItems().add(mImportFileButton);
mTopToolBar.getItems().add(new Separator(Orientation.VERTICAL));
}
/**
* Action to do on Import Image button click
*/
private void onImportFileButtonAction() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select a file to import");
fileChooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(this.getScene().getWindow());
if (selectedFile != null) {
importDataFile(selectedFile);
}
}
/**
* Imports an image file.
*
* @param file Image file.
*/
private void importDataFile(File file) {
try {
//check if file is too big
if (file.length() > 1024 * 1024) {
throw new VerifyError("File is too big.");
}
//get mime type of the file
String type = java.nio.file.Files.probeContentType(file.toPath());
byte[] data = new byte[(int) file.length()];
try (FileInputStream inputStream = new FileInputStream(file)) {
inputStream.read(data);
}
String base64data = Base64.getEncoder().encodeToString(data);
String htmlData = String.format(
"<embed src='data:%s;base64,%s' type='%s' />",
type, base64data, type);
//insert html
insertHtmlAfterCursor(htmlData);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
CustomHTMLEditorTest
import javafx.scene.text.Font;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CustomHTMLEditorTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
CustomHTMLEditor htmlEditor = new CustomHTMLEditor();
htmlEditor.setMaxHeight(Double.MAX_VALUE);
htmlEditor.setMaxWidth(Double.MAX_VALUE);
htmlEditor.setMinWidth(0);
htmlEditor.setMinHeight(0);
HBox.setHgrow(htmlEditor, Priority.ALWAYS);
VBox.setVgrow(htmlEditor, Priority.ALWAYS);
TextArea textArea = new TextArea();
textArea.setEditable(false);
//textArea.setFont(Font.font("Consolas", FontWeight.BOLD, FontPosture.REGULAR, 25));
textArea.setFont(new Font("Consolas", 14f));
TabPane root = new TabPane();
root.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
root.getTabs().add(new Tab(" Visual ", htmlEditor));
root.getTabs().add(new Tab(" HTML ", textArea));
root.getSelectionModel().selectedIndexProperty().addListener((event) -> {
textArea.setText(
htmlEditor.getHtmlText()
.replace("<", "\n<")
.replace(">", ">\n")
.replace("\n\n", "\n")
);
});
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("HTML Editor Test!");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Tác giả: Vàng Văn Quyn
Những tin mới hơn
Những tin cũ hơn
- Click vào nút hiển thị ngày trong tuần hoặc tháng âm lịch để xem chi tiết
- Màu đỏ: Ngày tốt
- Xanh lá: Đầu tháng âm lịch
- Màu vàng: Ngày hiện tại