How can I add a clickable URL in a JTextArea? - java

I am writing an application and in that I am using JTextArea to display some text. Now I want to show some clickable URL in text area along with the normal text and I want if user click on the URL then the web page that URL referring to should open in new web browser window.

Use JEditorPane with HTMLEditorKit or JTextPane and set content type to "text/html"

..url referring to should open in new web browser window.
// 1.6+
Desktop.getDesktop().browse(URI);

Here is an example of opening links from JTextArea:
JTextArea jtxa = new JTextArea(25,100);
JScrollPane jsp = new JScrollPane(jtxa);
JPanel jp = new JPanel();
jp.add(jsp);
jp.setSize(100,50);
jtxa.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
if(me.getClickCount()==2) //making sure there was a double click
{
int x = me.getX();
int y = me.getY();
int startOffset = jtxa.viewToModel(new Point(x, y));//where on jtextarea click was made
String text = jtxa.getText();
int searchHttp = 0;
int wordEndIndex = 0;
String[] words = text.split("\\s");//spliting the text to words. link will be a single word
for(String word:words)
{
if(word.startsWith("https://") || word.startsWith("http://"))//looking for the word representing the link
{
searchHttp = text.indexOf(word);
wordEndIndex = searchHttp+word.length();
if(startOffset>=searchHttp && startOffset<=wordEndIndex)//after the link word was found, making sure the double click was made on this link
{
try
{
jtxa.select(searchHttp, wordEndIndex);
desk.browse(new URI(word)); //opening the link in browser. Desktop desk = Desktop.getDesktop();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
}
});

Related

Java Aspose Slides find and replace text cannot keep text style

I'm working with: Aspose.Slides lib to read PPT and PPTX files.
When I replace text with another text, the font size is broken.
Origin:
After replace text:
public void asposeTranslate(String fileName) throws IOException {
Locale.setDefault(new Locale("en-us"));
// Load presentation
Presentation pres = new Presentation(URL + "/" + fileName);
// Loop through each slide
for (ISlide slide : pres.getSlides()) {
// Get all text frames in the slide
ITextFrame[] tf = SlideUtil.getAllTextBoxes(slide);
for (int i = 0; i < tf.length; i++) {
for (IParagraph para : tf[i].getParagraphs()) {
for (IPortion port : para.getPortions()) {
String originText = port.getText();
String newText = translateText(originTexmakes); // method make a new text
port.setText(newText); // replace with new text
}
}
}
}
pres.save(URL + "/new_" + fileName, SaveFormat.Pptx);
}
I read from blogs: https://blog.aspose.com/slides/find-and-replace-text-in-powerpoint-using-java/#API-to-Find-and-Replace-Text-in-PowerPoint
After replacing the new text, How can I keep older all styles of the older text?
I used aspose-slides-21.7
Thanks,
You can post the issue on Aspose.Slides forum, provide a sample presentation and get help. I am working as a Support Developer at Aspose.

print text from textArea useing javaFX Printer

I am try to print text from text Area using JavaFX Printer(Like in notepad printing feature). I want to print that text without textArea background styles. So I try it with another text area. I wrap its text for avoid x bar overflow. But, I can't find a way to avoid y bar overflow. also I can't hide the background. can some one help or give a subjections for this or any other way. This is my current code. Also I try to hide scroll bars using css. but it did't support. I want to print only the text.
TextArea txtArea = new TextArea("This is some long text..");
public void printText() {
PrinterJob job = PrinterJob.createPrinterJob();
if(job == null) {
System.out.println("Error");
return;
}
boolean proseed = job.showPrintDialog(root.getScene().getWindow());
JobSettings ss1 = job.getJobSettings();
PageLayout pageLayout1 = ss1.getPageLayout();
double pgW1 = pageLayout1.getPrintableWidth();
double pgH1 = pageLayout1.getPrintableHeight();
TextArea tempTxtArea = new TextArea(txtArea.getText());
tempTxtArea.setPrefSize(pgW1, pgH1);
tempTxtArea.setWrapText(true);
tempTxtArea.setId("tempScroolBar");
if(proseed) {
boolean printed = job.printPage(tempTxtArea);
if (printed) {
job.endJob();
} else {
System.out.println("Fail");
}
}
}
this is my css file
#tempScroolBar > .scroll-pane {
-fx-vbar-policy: never;
-fx-hbar-policy: never;
}
Update
I updated my code. But now I have another problem. I changed TextArea to Label and to print all the content(avoid y bar overflow) I want to get number of the pages. But it doesn't return height(always return 0). Then I refer https://stackoverflow.com/a/21075734/13862869 and I set It to the Scene. Without add the label to the new Scene it doesn't give the width. But when I set the label to the Scene only three '.' are print in my document. Can some one help me to solve this...
public void printText() {
PrinterJob job = PrinterJob.createPrinterJob();
if(job == null) {
System.out.println("Error");
return;
}
boolean proseed = job.showPrintDialog(root.getScene().getWindow());
JobSettings ss1 = job.getJobSettings();
PageLayout pageLayout1 = ss1.getPageLayout();
double pgW1 = pageLayout1.getPrintableWidth();
double pgH1 = pageLayout1.getPrintableHeight();
HBox h = new HBox();
Label tempText = new Label();
tempText.setPrefWidth(pgW1);
tempText.setWrapText(true);
tempText.setText(txtArea.getText());
h.getChildren().add(tempText);
Scene s = new Scene(h); // when i remove this line again text can print
tempText.applyCss();
double fullLabelHeight = tempText.prefHeight(-1);
int numberOfPages = (int) Math.ceil(fullLabelHeight/ pgH1);
if(proseed) {
job.printPage(tempText);
job.endJob();
}
}

IText 7 How To Add Div or Paragraph in Header Without Overlapping Page Content?

I am facing the following problem for which i haven't found any solution yet. I am implementing a platform for a medical laboratory. They want for every incident to write the report to the system and then generate and print it from the system. I am using itext 7 to accomplish this. However i am facing the following problem.
They have a very strange template. On the first page in the beginning they want to print a specific table, while in the beginning of every other page they want to print something else. So i need to know when pages change in order to print in the beginning of the page the corresponding table.
After reading various sources i ended up creating the first page normally and then adding a header event handler that checks the page number and gets executed always except page 1.
public class VariableHeaderEventHandler implements IEventHandler {
#Override
public void handleEvent(Event event) {
System.out.println("THIS IS ME: HEADER EVENT HANDLER STARTED.....");
PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
PdfDocument pdfDoc = documentEvent.getDocument();
PdfPage page = documentEvent.getPage();
Rectangle pageSize = page.getPageSize();
int pageNumber = pdfDoc.getPageNumber(page);
if (pageNumber == 1) return; //Do nothing in the first page...
System.out.println("Page size: " + pageSize.getHeight());
Rectangle rectangle = new Rectangle(pageSize.getLeft() + 30, pageSize.getHeight()-234, pageSize.getWidth() - 60, 200);
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
pdfCanvas.rectangle(rectangle);
pdfCanvas.setFontAndSize(FontsAndStyles.getRegularFont(), 10);
Canvas canvas = new Canvas(pdfCanvas, pdfDoc, rectangle);
Div header = new Div();
Paragraph paragraph = new Paragraph();
Text text = new Text("Διαγνωστικό Εργαστήριο Ιστοπαθολογίας και Μοριακής Παθολογοανατομικής").addStyle(FontsAndStyles.getBoldStyle());
paragraph.add(text);
paragraph.add(new Text("\n"));
text = new Text("Μοριακή Διάγνωση σε Συνεργασία με").addStyle(FontsAndStyles.getBoldStyle());
paragraph.add(text);
paragraph.add(new Text("\n"));
text = new Text("Γκούρβας Βίκτωρας, M.D., Ph.D.").addStyle(FontsAndStyles.getBoldStyle());
paragraph.add(text);
paragraph.add(new Text("\n"));
text = new Text("Τσιμισκή 33, Τ.Κ. 54624, ΘΕΣΣΑΛΟΝΙΚΗ").addStyle(FontsAndStyles.getNormalStyle());
paragraph.add(text);
paragraph.add(new Text("\n"));
text = new Text("Τήλ/Φάξ: 2311292924 Κιν.: 6932104909 e-mail: vgourvas#gmail.com").addStyle(FontsAndStyles.getNormalStyle());
paragraph.add(text);
header.add(paragraph);
// =============Horizontal Line BOLD============
SolidLine solidLine = new SolidLine((float) 1.5);
header.add(new LineSeparator(solidLine));
// ========Horizontal Line BOLD End==========
text = new Text("ΠΑΘΟΛΟΓΟΑΝΑΤΟΜΙΚΗ ΕΞΕΤΑΣΗ").addStyle(FontsAndStyles.getBoldStyle());
paragraph = new Paragraph().add(text);
header.add(paragraph);
header.setTextAlignment(TextAlignment.CENTER);
canvas.add(header);
canvas.close();
}
However the problem i am facing now is that header overlaps content and i can't figure out how to set different margins per page. For example form page 2 and beyond i would like different topMargin.
Has anyone faced these problems before and have found a working solution? Am I implementing correct? Is there a better way of accomplishing the same result?
Thanks in advance,
Toutoudakis Michail
You should create your own custom document renderer and decrease the area which would be used to place content for each page except for the first one.
Please look at the snippet below and updateCurrentArea method in particular.
class CustomDocumentRenderer extends DocumentRenderer {
public CustomDocumentRenderer(Document document) {
super(document);
}
#Override
public IRenderer getNextRenderer() {
return new CustomDocumentRenderer(this.document);
}
#Override
protected LayoutArea updateCurrentArea(LayoutResult overflowResult) {
LayoutArea area = super.updateCurrentArea(overflowResult);
if (currentPageNumber > 1) {
area.setBBox(area.getBBox().decreaseHeight(200));
}
return area;
}
}
Then just set the renderer on your document:
Document doc = new Document(pdfDoc);
doc.setRenderer(new CustomDocumentRenderer(doc));
The resultant pdf which I get for your document looks as follows:
There is another solution however. Once you've added at least one element to your document, you can change the default document's margins. The change will be applied on all pages created afterwards (and in your case these are pages 2, 3, ...)
doc.add(new Paragraph("At least one element should be added. Otherwise the first page wouldn't be created and changing of the default margins would affect it."));
doc.setMargins(200, 36, 36, 36);
// now you can be sure that all the next pages would have new margins

Setting multi-line text to form fields in PDFBox

I'm using PDFBox to fill form fields in a pdf using below code:
PDField nameField = form.getField("name");
if(null != nameField){
nameField.setValue(data.get("name")); // data is a hashmap
nameField.setReadonly(true);
}
The problem is, if the text is long it doesn't split to multiple lines, even though I have enabled the "multi-line" option for the field in the pdf. Do I have to do anything from the code as well to enable this?
Thanks.
Remember
Setting the ressources for the fonts to be used into the TextField.
Associating the ressources with the PDAccroform of the PDDocument.
Getting a widget for the PDTextField.
Getting a rectangle for the Widget.
Setting the width and the height of the rectangle of the widget.
It would solve it. In my case, I have a height of 20 for a non multiline text and another of 80 for a multiline textfield.You can see them being the last argument of the PDRectangle constructor. The PDRectangle class is used to specify the position and the dimension of the widget that sets it's rectangle to it. The texfield widget will appear as specified by the PDRectangle.
public static PDTextField addTextField(PDDocument pdDoc,PDAcroForm pda,String value,
String default_value,Boolean multiline,float txtfieldsyposition,float pagesheight)
{
int page = (int) (txtfieldsyposition/pagesheight);
if(page+1> pdDoc.getNumberOfPages())
{
ensurePageCapacity(pdDoc,page+1);//add 1 page to doc if needed
}
PDTextField pdtff = new PDTextField(pda);
PDFont font = new PDType1Font(FontName.TIMES_ROMAN);
String appearance = "/TIMES 10 Tf 0 0 0 rg";
try
{
PDFont font_ = new PDType1Font(FontName.HELVETICA);
PDResources resources = new PDResources();
resources.put(COSName.getPDFName("Helv"), font_);
resources.put(COSName.getPDFName("TIMES"), font);
pda.setDefaultResources(resources);
org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget widget = pdtff.getWidgets().get(0);
PDRectangle rect = null;
if(!multiline)
rect = new PDRectangle(80, (pagesheight - (txtfieldsyposition % pagesheight)), 450, 20);
else
rect = new PDRectangle(80,(pagesheight-(txtfieldsyposition%pagesheight)),450,80);
PDPage pd_page = pdDoc.getPage(page);
System.out.println(pd_page.getBBox().getHeight());
widget.setRectangle(rect);
widget.setPage(pd_page);
PDAppearanceCharacteristicsDictionary fieldAppearance = new PDAppearanceCharacteristicsDictionary(new COSDictionary());
fieldAppearance.setBorderColour(new PDColor(new float[]{0,0,0}, PDDeviceRGB.INSTANCE));
fieldAppearance.setBackground(new PDColor(new float[]{255,255,255}, PDDeviceRGB.INSTANCE));
widget.setAppearanceCharacteristics(fieldAppearance);
widget.setPrinted(true);
pd_page.getAnnotations().add(widget);
System.out.println("before appearance " +pdtff.getDefaultAppearance());
pdtff.setDefaultAppearance(appearance);
System.out.println("after appearance "+pdtff.getDefaultAppearance());
if(multiline)
{
pdtff.setMultiline(true);
}
pdtff.setDefaultValue("");
pdtff.setValue(value.replaceAll("\u202F"," "));
pdtff.setPartialName( page +""+(int)txtfieldsyposition);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
}
return pdtff;
}

Add bookmarks in PDF files using PDFRenderer API

I am using PDF Render for reading and updating PDF.
I want to add bookmark in that PDF and update it using same API.
Is it possible to do so with PDF Renderer?
Here is some code snippet to update bookmarks in PDF which is not working
File file = new File("C:\\test.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
OutlineNode rootNode = new OutlineNode("New Bookmark");
PDFPage page = pdffile.getPage(0);
OutlineNode node = pdffile.getOutline();
OutlineNode node2 = (OutlineNode)node.getNextNode();
node2.add(rootNode);
I am using PDFRenderer-0.9.0.jar lib for above example.
If any one worked on PDF Renderer, please suggest me.
You can add a bookmark using this.
For full code and implementation follow the link.
you can use follow the link if you want to access the bookmark later.
import pdftron.Common.PDFNetException;
import pdftron.PDF.*;
import pdftron.SDF.Obj;
import pdftron.SDF.SDFDoc;
public class BookmarkTest {
public static void main(String[] args)
{
PDFNet.initialize();
// Relative path to the folder containing test files.
String input_path = "../../TestFiles/";
String output_path = "../../TestFiles/Output/";
// The following example illustrates how to create and edit the outline tree
// using high-level Bookmark methods.
try
{
PDFDoc doc=new PDFDoc((input_path + "numbered.pdf"));
doc.initSecurityHandler();
// Lets first create the root bookmark items.
Bookmark red = Bookmark.create(doc, "Red");
Bookmark green = Bookmark.create(doc, "Green");
Bookmark blue = Bookmark.create(doc, "Blue");
doc.addRootBookmark(red);
doc.addRootBookmark(green);
doc.addRootBookmark(blue);
// You can also add new root bookmarks using Bookmark.AddNext("...")
blue.addNext("foo");
blue.addNext("bar");
// We can now associate new bookmarks with page destinations:
// The following example creates an 'explicit' destination (see
// section '8.2.1 Destinations' in PDF Reference for more details)
Destination red_dest = Destination.createFit((Page)(doc.getPageIterator().next()));
red.setAction(Action.createGoto(red_dest));
// Create an explicit destination to the first green page in the document
green.setAction(Action.createGoto(
Destination.createFit((Page)(doc.getPage(10))) ));
// The following example creates a 'named' destination (see
// section '8.2.1 Destinations' in PDF Reference for more details)
// Named destinations have certain advantages over explicit destinations.
byte[] key={'b','l','u','e','1'};
Action blue_action = Action.createGoto(key,
Destination.createFit((Page)(doc.getPage(19))) );
blue.setAction(blue_action);
// We can now add children Bookmarks
Bookmark sub_red1 = red.addChild("Red - Page 1");
sub_red1.setAction(Action.createGoto(Destination.createFit((Page)(doc.getPage(1)))));
Bookmark sub_red2 = red.addChild("Red - Page 2");
sub_red2.setAction(Action.createGoto(Destination.createFit((Page)(doc.getPage(2)))));
Bookmark sub_red3 = red.addChild("Red - Page 3");
sub_red3.setAction(Action.createGoto(Destination.createFit((Page)(doc.getPage(3)))));
Bookmark sub_red4 = sub_red3.addChild("Red - Page 4");
sub_red4.setAction(Action.createGoto(Destination.createFit((Page)(doc.getPage(4)))));
Bookmark sub_red5 = sub_red3.addChild("Red - Page 5");
sub_red5.setAction(Action.createGoto(Destination.createFit((Page)(doc.getPage(5)))));
Bookmark sub_red6 = sub_red3.addChild("Red - Page 6");
sub_red6.setAction(Action.createGoto(Destination.createFit((Page)(doc.getPage(6)))));
// Example of how to find and delete a bookmark by title text.
Bookmark foo = doc.getFirstBookmark().find("foo");
if (foo.isValid())
{
foo.delete();
}
else
{
throw new Exception("Foo is not Valid");
}
Bookmark bar = doc.getFirstBookmark().find("bar");
if (bar.isValid())
{
bar.delete();
}
else
{
throw new Exception("Bar is not Valid");
}
// Adding color to Bookmarks. Color and other formatting can help readers
// get around more easily in large PDF documents.
red.setColor(1, 0, 0);
green.setColor(0, 1, 0);
green.setFlags(2); // set bold font
blue.setColor(0, 0, 1);
blue.setFlags(3); // set bold and itallic
doc.save((output_path + "bookmark.pdf"), 0, null);
doc.close();
}
catch(Exception e)
{
System.out.println(e);
}
// The following example illustrates how to traverse the outline tree using
// Bookmark navigation methods: Bookmark.GetNext(), Bookmark.GetPrev(),
// Bookmark.GetFirstChild () and Bookmark.GetLastChild ().
try
{
// Open the document that was saved in the previous code sample
PDFDoc doc=new PDFDoc((output_path + "bookmark.pdf"));
doc.initSecurityHandler();
Bookmark root = doc.getFirstBookmark();
PrintOutlineTree(root);
doc.close();
System.out.println("Done.");
}
catch(Exception e)
{
System.out.println(e);
}
// The following example illustrates how to create a Bookmark to a page
// in a remote document. A remote go-to action is similar to an ordinary
// go-to action, but jumps to a destination in another PDF file instead
// of the current file. See Section 8.5.3 'Remote Go-To Actions' in PDF
// Reference Manual for details.
try
{
// Open the document that was saved in the previous code sample
PDFDoc doc=new PDFDoc((output_path + "bookmark.pdf"));
doc.initSecurityHandler();
// Create file specification (the file reffered to by the remote bookmark)
Obj file_spec = doc.createIndirectDict();
file_spec.putName("Type", "Filespec");
file_spec.putString("F", "bookmark.pdf");
FileSpec spec=new FileSpec(file_spec);
Action goto_remote = Action.createGotoRemote(spec, 5, true);
Bookmark remoteBookmark1 = Bookmark.create(doc, "REMOTE BOOKMARK 1");
remoteBookmark1.setAction(goto_remote);
doc.addRootBookmark(remoteBookmark1);
// Create another remote bootmark, but this time using the low-level SDF/Cos API.
// Create a remote action
Bookmark remoteBookmark2 = Bookmark.create(doc, "REMOTE BOOKMARK 2");
doc.addRootBookmark(remoteBookmark2);
Obj gotoR = remoteBookmark2.getSDFObj().putDict("A");
{
gotoR.putName("S","GoToR"); // Set action type
gotoR.putBool("NewWindow", true);
// Set the file specification
gotoR.put("F", file_spec);
// jump to the first page. Note that pages are indexed from 0.
Obj dest = gotoR.putArray("D"); // Set the destination
dest.pushBackNumber(9);
dest.pushBackName("Fit");
}
doc.save((output_path + "bookmark_remote.pdf"), SDFDoc.e_linearized, null);
doc.close();
}
catch(Exception e)
{
System.out.println(e);
}
PDFNet.terminate();
}
static void PrintIndent(Bookmark item) throws PDFNetException
{
int ident = item.getIndent() - 1;
for (int i=0; i<ident; ++i) System.out.print( " ");
}
// Prints out the outline tree to the standard output
static void PrintOutlineTree(Bookmark item) throws PDFNetException
{
for (; item.isValid(); item=item.getNext())
{
PrintIndent(item);
System.out.print((item.isOpen() ? "- " : "+ ") + item.getTitle() + " ACTION -> ");
// Print Action
Action action = item.getAction();
if (action.isValid())
{
if (action.getType() == Action.e_GoTo)
{
Destination dest = action.getDest();
if (dest.isValid())
{
Page page = dest.getPage();
System.out.println("GoTo Page #" + page.getIndex());
}
}
else
{
System.out.println("Not a 'GoTo' action");
}
}
else
{
System.out.println("NULL");
}
if (item.hasChildren()) // Recursively print children sub-trees
{
PrintOutlineTree(item.getFirstChild());
}
}
}
}

Categories

Resources