Skip to content

Instantly share code, notes, and snippets.

@xtrcode
Created March 8, 2019 18:27
Show Gist options
  • Save xtrcode/35d9874061cc4d970ee8a678cde10ae3 to your computer and use it in GitHub Desktop.
Save xtrcode/35d9874061cc4d970ee8a678cde10ae3 to your computer and use it in GitHub Desktop.
Write clipboard content into pdf Java
package com.company;
import java.awt.*;
import java.io.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
// get clipboard content
String clipboard = Main.getClipBoard();
// create pdf and write clipboard into
Main.createPdfFromClipboard(clipboard, "my.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create pdf file based on the given name and write the given content into it.
*
* @param clipboard Text to write into pdf
* @param pdfName Pdf file name (incl. absolute Path but optional)
*/
private static void createPdfFromClipboard(String clipboard, String pdfName) {
try {
System.out.println("Convert text file to pdf");
System.out.println("output : " + pdfName);
// create new document
Document document = new Document(PageSize.LETTER, 40, 40, 40, 40);
// create new pdf writer for document
PdfWriter.getInstance(document, new FileOutputStream(pdfName));
// open document
document.open();
// set pdf properties (optional)
document.addAuthor("Author");
document.addSubject("My Subject");
document.addTitle("My Title");
// write clipboard content to pdf
BufferedReader input = new BufferedReader(new StringReader(clipboard));
String line = "";
while (null != (line = input.readLine())) {
Paragraph p = new Paragraph(line);
p.setAlignment(Element.ALIGN_JUSTIFIED);
document.add(p);
}
// close reader
input.close();
// close document
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get the content of the users clipboard and return it as string
*
* @return String - Clipboard content
*/
private static String getClipBoard() throws Exception {
try {
return (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
throw new Exception("Cant read from clipboard.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment