Here is the code.
-------- Forwarded Message --------
Subject: Fwd: flattening
Date: Wed, 23 Jun 2021 13:12:18 +0200
From: Ranjeet Kuruvilla <[email protected]>
To: [email protected]
I finally manage to send samples to showcase the flattening problem.
As one can see, flattening did not remove the fields. One can see that
the field names are stil there.
The Flattening of the fields did not work.
Expected Results
I expected all fields, that were read only to be removed. Itext 2.1.7
does exactly that.
Actual Results
The fields, that were readonly, are still there. That is not what
flattening is about!
Thanks
package defaultPackage;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceCharacteristicsDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDCheckBox;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDRadioButton;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfName;
/**
* MainFrame
*
* @author F-Sebastian.Felsl
* @version $Revision:$<br/>
* $Date:$<br/>
* $Author:$
*/
public class PDFFlatteningBug extends JFrame
{
protected static final Logger LOGGER = Logger.getLogger(PDFFlatteningBug.class);
/** serialVersionUID */
protected static final long serialVersionUID = 1L;
private ClassLoader cl = getClass().getClassLoader();
static class ConfirmationDialog
{
/** OHNE_RISIKOFRAGEN */
public static final String OHNE_RISIKOFRAGEN = "Vor Unterzeichnung des Antrags habe ich alle Angaben auf Vollständigkeit und Richtigkeit überprüft. Ich habe die Schlusserklärung im Antrag zur Kenntnis genommen.";
/** MIT_RISIKOFRAGEN */
public static final String MIT_RISIKOFRAGEN =
"Vor Unterzeichnung des Antrags habe ich alle Angaben auf Vollständigkeit und Richtigkeit überprüft. Die in Textform gestellten Fragen habe ich wahrheitsgemäß und vollständig beantwortet. Auf die Folgen einer Anzeigepflichtverletzung wurde ich hingewiesen und ich habe die 'Mitteilung nach § 19 Abs. 5 VVG über die Folgen einer Verletzung der vorvertraglichen Anzeigepflicht' vor Beantwortung der Fragen gelesen. Ich habe die Schlusserklärung im Antrag zur Kenntnis genommen.";
}
/** Die OPEN_FIELD_FLAG. */
public static final String OPEN_FIELD_FLAG = new String("OF");
/** UNTERSCHRIFT_ANTRAG */
private static final String UNTERSCHRIFT_ANTRAG = "UNTERSCHRIFT_ANTRAG_";
/** UNTERSCHRIFT_VN_FELD_ID */
public static final String UNTERSCHRIFT_VN_FELD_ID = UNTERSCHRIFT_ANTRAG + "VN";
/** UNTERSCHRIFT_ANTRAG_BEITRAGSZAHLER */
public static final String UNTERSCHRIFT_BZ_FELD_ID = UNTERSCHRIFT_ANTRAG + "BEITRAGSZAHLER";
/** NORMAL_CAPTION */
public static final String NORMAL_CAPTION = COSName.U.getName().toLowerCase(); // 8 = cross; 4 = checkmark; H = star; u = diamond; n = square, l = dot
/** CHECKBOX_FONT */
public static final PDType1Font CHECKBOX_FONT = PDType1Font.ZAPF_DINGBATS;
/** TEXTFIELD_FONT */
public static final PDType1Font TEXTFIELD_FONT = PDType1Font.HELVETICA_BOLD_OBLIQUE;
/** CHECKBOX_FONTTYPE */
public static final COSName CHECKBOX_FONTTYPE = COSName.getPDFName(CHECKBOX_FONT.getName());
/** TEXTFIELD_FONTTYPE */
public static final COSName TEXTFIELD_FONTTYPE = COSName.getPDFName(TEXTFIELD_FONT.getName());
/** TEXTFIELD_HELV */
public static final COSName TEXTFIELD_HELV = COSName.getPDFName("Helv");
/** checkBoxGlyph */
public static String checkBoxGlyph;
/** textfieldStyle */
public static String textfieldStyle;
/** textFieldStyle */
public static String textFieldCOSName;
/** CHECKBOX_STYLE */
public static String checkboxStyle;
/** checkBoxStyle */
public static String checkBoxCOSName;
/**
* Bestätigungsdialog. Ist ein Text gesetzt MUSS dieser vor dem Unterschreiben angezeigt und vom
* Benutzer bestätigt werden
*/
public static final PdfName PRESIGN_CONFIRMATION_MESSAGE =
new PdfName("bPRO_preSigningConfirmationMessage"); // Flag muss ein PDFString sein
/** RED */
public static final float RED = 57 / 255f;
/** GREEN */
public static final float GREEN = 178 / 255f;
/** BLUE */
public static final float BLUE = 255 / 255f;
/** MARK_COLOR */
public static final PDColor MARK_COLOR = new PDColor(new float[] { RED, GREEN, BLUE }, PDDeviceRGB.INSTANCE);
private static final String FONTTYPE_KEYWORD = "<fontType>";
private static final String FONTSIZE_KEYWORD = "<size>";
private static final String COL = "/" + FONTTYPE_KEYWORD + " " + FONTSIZE_KEYWORD + " " + "Tf" + " " + RED + " " + GREEN + " " + BLUE + " " + "rg";
/** standardSecurityHandler */
public static StandardSecurityHandler standardSecurityHandler;
/** spp */
public static StandardProtectionPolicy spp;
private JPanel listOfFiles = new JPanel();
private final List<String> fileList = Arrays.asList("SourceOK.pdf", "SourceFailure.pdf");
static
{
generateStyles();
}
/** windowAdapter */
private final WindowAdapter windowAdapter = new WindowAdapter()
{
@Override
public void windowClosed(WindowEvent e)
{
System.exit(0);
}
};
private static String createStyle(PDType1Font font, int size)
{
return COL.replace(FONTTYPE_KEYWORD, font.getName()).replace(FONTSIZE_KEYWORD, String.valueOf(size));
}
private static void generateStyles()
{
System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "20971520"); // 20 MegaByte
textfieldStyle = createStyle(TEXTFIELD_FONT, 0);
checkboxStyle = createStyle(CHECKBOX_FONT, 10);
try
{
checkBoxGlyph = CHECKBOX_FONT.getGlyphList().toUnicode(CHECKBOX_FONT.codeToName(NORMAL_CAPTION.codePointAt(0)));
}
catch (IOException e)
{
e.printStackTrace();
}
}
private final FileFilter FILTER = new FileNameExtensionFilter(".pdf", "pdf");
private final ActionListener convertListener = e -> convert();
private JLabel choosePdfsLabel = new JLabel("");
/**
* MainFrame Konstruktor.
*
*/
public PDFFlatteningBug()
{
super("Flattener");
build();
}
private void build()
{
setLayout(new BorderLayout());
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
addWindowListener(windowAdapter);
add(createButtonPanel(), BorderLayout.CENTER);
setVisible(true);
}
private JPanel createButtonPanel()
{
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(choosePdfsLabel);
listOfFiles.setBorder(BorderFactory.createTitledBorder("Liste der Unterschriften-Namen"));
listOfFiles.setAlignmentX(Component.LEFT_ALIGNMENT);
listOfFiles.setLayout(new BoxLayout(listOfFiles, BoxLayout.Y_AXIS));
buttonPanel.add(listOfFiles);
buttonPanel.add(new JSeparator());
JButton convert = new JButton("Dateien konvertieren");
convert.addActionListener(convertListener);
buttonPanel.add(convert);
return buttonPanel;
}
/**
* @param acroFields acroFields
* @return boolean
*/
public boolean isValidAcroFields(AcroFields acroFields)
{
return acroFields != null && acroFields.getFields() != null && !acroFields.getFields()
.isEmpty();
}
private void prepareSpecialFields(PDDocument document, boolean withFlattening, boolean withFlatteningAndRefresh)
{
try
{
if (document == null)
{
return;
}
final PDDocumentCatalog catalog = document.getDocumentCatalog();
if (catalog == null)
{
return;
}
PDAcroForm acroForm = catalog.getAcroForm(null);
if (acroForm == null || acroForm.getFields() == null || acroForm.getFields()
.isEmpty())
{
return;
}
PDResources res = acroForm.getDefaultResources();
if (res == null)
{
res = new PDResources();
}
res.put(TEXTFIELD_FONTTYPE, TEXTFIELD_FONT);
res.put(CHECKBOX_FONTTYPE, CHECKBOX_FONT);
acroForm.setDefaultResources(res);
final List<PDField> acroFieldsNonEdit = new ArrayList<>();
final List<PDField> acroFieldsEdit = new ArrayList<>();
for (int i = acroForm.getFields()
.size() - 1; i >= 0; i--)
{
PDField field = acroForm.getFields()
.get(i);
if (!((field instanceof PDTextField) || (field instanceof PDCheckBox)
|| (field instanceof PDRadioButton)))
{
LOGGER.debug("Feld " + field.getFullyQualifiedName()
+ " is not relevant and will not be altered.");
continue;
}
if (field.isReadOnly())
{
acroFieldsNonEdit.add(field);
LOGGER.debug(
"Feld " + field.getFullyQualifiedName() + " is readonly and will be flattened.");
}
else
{
acroFieldsEdit.add(field);
if (field instanceof PDTextField)
{
LOGGER.debug("Textfield " + field.getFullyQualifiedName() + " is not readonly.");
markTextfield(field);
}
else if (field instanceof PDCheckBox)
{
LOGGER.debug("Checkbox " + field.getFullyQualifiedName() + " is not readonly.");
markCheckBox(document, field);
}
else if (field instanceof PDRadioButton)
{
LOGGER.debug("Checkbox " + field.getFullyQualifiedName() + " is not readonly.");
markCheckBox(document, field);
}
}
}
if(withFlattening)
{
acroForm.flatten(acroFieldsNonEdit, withFlatteningAndRefresh); // refreshAppearance = false will make the document
// unusable in eDocBox!
}
acroForm.refreshAppearances(acroFieldsEdit);
acroForm.setNeedAppearances(true);
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
/**
* @param content content
* @return PDDocument
* @throws Exception Exception
*/
public PDDocument transformToPdf(byte[] content) throws Exception
{
@SuppressWarnings("unused")
PDDocument reader = PDDocument.load(content);
// reader.setVersion(1.8f);// PDF
// einlesen
// um es
// auf
// Integrität
// zu
// prüfen
return reader;
}
/**
* @param mitRisikofragen mitRisikofragen
* @return COSString
*/
public static String selectSignatureMessage(boolean mitRisikofragen)
{
return mitRisikofragen ? ConfirmationDialog.MIT_RISIKOFRAGEN
: ConfirmationDialog.OHNE_RISIKOFRAGEN;
}
private void attachCheckBoxAppearanceStream(PDDocument document, PDAnnotationWidget widget)
{
PDAppearanceDictionary apD = widget.getAppearance();
if (apD == null)
{
apD = new PDAppearanceDictionary();
widget.setAppearance(apD);
}
try
{
PDAppearanceCharacteristicsDictionary acD = widget.getAppearanceCharacteristics();
if (acD == null)
{
acD = new PDAppearanceCharacteristicsDictionary(widget.getCOSObject());
widget.setAppearanceCharacteristics(acD);
}
PDBorderStyleDictionary bD = widget.getBorderStyle();
if (bD == null)
{
bD = new PDBorderStyleDictionary(widget.getCOSObject());
widget.setBorderStyle(bD);
}
acD.setNormalCaption(NORMAL_CAPTION);
acD.setAlternateCaption(NORMAL_CAPTION);
acD.setRolloverCaption(NORMAL_CAPTION);
final float lineWidth = getLineWidth(widget);
final PDRectangle rect = widget.getRectangle();
bD.setWidth(lineWidth);
bD.setStyle(PDBorderStyleDictionary.STYLE_SOLID);
PDAppearanceStream aS = new PDAppearanceStream(document);
aS.setBBox(new PDRectangle(rect.getWidth(), rect.getHeight()));
PDResources res = new PDResources();
res.add(CHECKBOX_FONT);
aS.setResources(res);
aS.setFormType(1);
PDPageContentStream pcAPCS = new PDPageContentStream(document, aS);
pcAPCS.setLineWidth(lineWidth); // border style (dash) ignored
pcAPCS.addRect(0, 0, rect.getWidth(), rect.getHeight());
pcAPCS.beginText();
pcAPCS.setFont(CHECKBOX_FONT, rect.getHeight());
pcAPCS.setStrokingColor(MARK_COLOR);
pcAPCS.setNonStrokingColor(MARK_COLOR);
pcAPCS.newLineAtOffset(lineWidth * 2, lineWidth * 2);
pcAPCS.showText(checkBoxGlyph);
pcAPCS.endText();
pcAPCS.close();
final COSDictionary normalAppearanceDict =
(COSDictionary) (apD.getNormalAppearance()).getCOSObject();
final COSDictionary downAppearanceDict =
(COSDictionary) (apD.getDownAppearance()).getCOSObject();
final COSDictionary rollAppearanceDict =
(COSDictionary) (apD.getRolloverAppearance()).getCOSObject();
normalAppearanceDict.keySet()
.stream()
.forEach(x -> normalAppearanceDict.setItem(x, aS));
rollAppearanceDict.keySet()
.stream()
.forEach(x -> rollAppearanceDict.setItem(x, aS));
downAppearanceDict.keySet()
.stream()
.forEach(x -> downAppearanceDict.setItem(x, aS));
}
catch (IOException exception)
{
}
}
private float getLineWidth(PDAnnotationWidget widget)
{
PDBorderStyleDictionary bs = widget.getBorderStyle();
return (bs != null) ? bs.getWidth() : 1;
}
private void changeColor(COSDictionary dict, String style)
{
dict.setString(COSName.DA, style);
dict.setString(COSName.DS, style);
dict.setNeedToBeUpdated(true);
}
private void attachOpenFieldFlag(COSDictionary dict)
{
dict.setBoolean(OPEN_FIELD_FLAG, true);
dict.setNeedToBeUpdated(true);
}
private void markCheckBox(PDDocument document, PDField field)
{
// changeColor(field.getCOSObject(), BiProFieldManipulator.checkboxStyle);
List<PDAnnotationWidget> widgets = field.getWidgets();
if (widgets == null)
{
return;
}
LOGGER.debug("Checkbox " + field.getFullyQualifiedName() + " has " + widgets.size() + ".");
for (PDAnnotationWidget widget : widgets)
{
changeColor(widget.getCOSObject(), checkboxStyle);
attachCheckBoxAppearanceStream(document, widget);
attachOpenFieldFlag(widget.getCOSObject());
}
}
private void markTextfield(PDField field)
{
// changeColor(field.getCOSObject(), BiProFieldManipulator.textfieldStyle);
List<PDAnnotationWidget> widgets = field.getWidgets();
if (widgets == null)
{
return;
}
LOGGER.debug("Textfeld " + field.getFullyQualifiedName() + " has " + widgets.size() + ".");
for (PDAnnotationWidget widget : widgets)
{
changeColor(widget.getCOSObject(), textfieldStyle);
attachOpenFieldFlag(widget.getCOSObject());
}
}
private byte[] process(byte[] content, boolean withFlattening, boolean withFlatteningAndRefresh) throws Exception
{
PDDocument document = transformToPdf(content);
prepareSpecialFields(document, withFlattening, withFlatteningAndRefresh);
byte[] result = docToByte(document);
return result;
}
/**
* @param document document
* @return byte[]
*/
public byte[] docToByte(PDDocument document)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
try
{
document.save(out);
LOGGER.debug("Bytearray size " + out.size());
}
catch(Exception exception)
{
LOGGER.debug("Document was not written into a bytearraystream");
}
byte[] pdfData = null;
try
{
pdfData = out.toByteArray();
out.close();
}
catch(Exception exception)
{
LOGGER.debug("The bytearraystream was not written into a bytearray");
}
finally
{
out = null;
}
return pdfData;
}
private URL readFilePath(String filename)
{
return cl.getResource("Beispiele/" + filename);
}
private byte[] readInFile(URL url)
{
try
{
return IOUtils.toByteArray(url);
}
catch (IOException e)
{
}
return null;
}
private void writeBack(byte[] result, URL url, String resultFilename)
{
String s = null;
try
{
FileUtils.writeByteArrayToFile(Paths.get(".", "results", resultFilename.replace("Source", "Result")).toFile(), result);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void readInFiles()
{
for(String s: fileList)
{
final URL url = readFilePath(s);
final byte[] content = readInFile(url);
try
{
writeBack(process(content, false, false), url, s.replace(".pdf", "_without_flattening.pdf"));
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
writeBack(process(content, true, false), url, s.replace(".pdf", "_with_flattening.pdf"));
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
writeBack(process(content, true, true), url, s.replace(".pdf", "_with_flattening_and_refresh.pdf"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private void convert()
{
readInFiles();
}
}
package defaultPackage;
/**
* MainFrame
*
* @author F-Sebastian.Felsl
* @version $Revision:$<br/>
* $Date:$<br/>
* $Author:$
*/
public class Main
{
public static PDFFlatteningBug changer;
/**
* main
*
* @param args
*/
public static void main(String[] args)
{
changer = new PDFFlatteningBug();
}
}package defaultPackage;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
/**
* Utils
*
* @author F-Sebastian.Felsl
* @version $Revision:$<br/>
* $Date:$<br/>
* $Author:$
*/
public class Utils
{
/** CHARSET */
public static final Charset CHARSET = StandardCharsets.UTF_8;
/** DOCUMENT_FILES */
public static final String[] DOCUMENT_FILES = (String[]) Arrays.asList("pdf", "xml")
.toArray();
/** DOCUMENT_FILTERS */
public static final FileFilter DOCUMENT_FILTERS =
new FileNameExtensionFilter(".pdf, .png, .jpg", DOCUMENT_FILES);
/** XML_FILTERS */
public static final FileFilter XML_FILTERS = new FileNameExtensionFilter(".xml", "xml");
/** STANDARD_PATH */
public static final String STANDARD_PATH = Paths.get(".")
.normalize()
.toAbsolutePath()
.toString();
/** RESULTS_STANDARD_PATH */
public static final String RESULTS_STANDARD_PATH = Paths.get(STANDARD_PATH, "results")
.normalize()
.toAbsolutePath()
.toString();
/**
* @param path
* @param subPath
* @return
*/
public static Path createFolder(Path path, String subPath)
{
final Path currentPath = Paths.get((path == null) ? RESULTS_STANDARD_PATH
: path.toAbsolutePath()
.toString(),
subPath);
final File parent = currentPath.toFile()
.getParentFile();
if (!parent.exists())
{
return null;
}
if (currentPath.toFile()
.exists())
{
return currentPath;
}
if (currentPath.toFile()
.mkdirs())
{
return currentPath;
}
return null;
}
/**
* @param name
* @return
*/
public static File extractWorkingDirectory(String name)
{
String homeFolder = Paths.get(Utils.STANDARD_PATH)
.toFile()
.getAbsolutePath();
if (name == null || name.isEmpty())
{
return new File(homeFolder);
}
File path = new File(name);
return new File(path.exists() ? path.getPath() : homeFolder);
}
/**
* @param xml
* @return SOAPMessage
* @throws SOAPException
* @throws IOException
*/
public static SOAPMessage getSoapMessageFromString(String xml) throws SOAPException, IOException
{
return javax.xml.soap.MessageFactory.newInstance()
.createMessage(new MimeHeaders(), new ByteArrayInputStream(xml.getBytes(CHARSET)));
}
/**
* @param path
* @return
*/
public static List<File> collectPDFsFromDirectory(String path)
{
String[] paths = path.split("\n");
if (paths.length > 1)
{
List<File> files = new ArrayList<>();
for (String p : paths)
{
File file2 = new File(p);
if (file2.exists())
{
files.add(file2);
}
}
return files;
}
else if (paths.length == 1)
{
final File file = new File(paths[0]);
if (!file.exists())
{
return null;
}
else if (file.isDirectory())
{
return (List<File>) (FileUtils.listFiles(file, Utils.DOCUMENT_FILES, true));
}
else
{
return Arrays.asList(file);
}
}
else
{
return null;
}
}
/**
* @param parent
* @param fileName
* @param title
* @param filter
* @param extensionList
* @param type
* @return
*/
public static String showSaveFileSelector(Component parent, String fileName, String title,
FileFilter filter, int type)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setDialogTitle(title);
fileChooser.setFileSelectionMode(type);
fileChooser.setFileFilter(filter);
fileChooser.setCurrentDirectory(Utils.extractWorkingDirectory(fileName));
return fileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION
? fileChooser.getSelectedFile()
.getAbsolutePath()
: null;
}
/**
* @param parent
* @param fileName
* @param title
* @param filter
* @param extensionList
* @param multifileselection
* @param type
* @return
*/
public static File[] showLoadFileSelector(Component parent, String fileName, String title,
FileFilter filter, boolean multifileselection, int type)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
fileChooser.setFileSelectionMode(type);
fileChooser.setMultiSelectionEnabled(multifileselection);
fileChooser.setFileFilter(filter);
fileChooser.setCurrentDirectory(Utils.extractWorkingDirectory(fileName));
File[] selectedFiles = null;
if (fileChooser.showOpenDialog(parent) != JFileChooser.APPROVE_OPTION)
{
return null;
}
if (fileChooser.getSelectedFiles() != null && multifileselection)
{
selectedFiles = fileChooser.getSelectedFiles();
}
else if (fileChooser.getSelectedFile() != null)
{
selectedFiles = (new File[] { fileChooser.getSelectedFile() });
}
return (selectedFiles != null && selectedFiles.length > 0) ? selectedFiles : null;
}
/**
* @param text text
*/
public static void copyTextFromTextArea(String text)
{
Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(new StringSelection(text), null);
}
/**
* getStringFromSoapMessage
*
* @param soapMessage
* @return StringFromSoapMessage
* @throws SOAPException
* @throws IOException
*/
public static String getStringFromSoapMessage(SOAPMessage soapMessage)
throws SOAPException, IOException
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
soapMessage.writeTo(bout);
return new String(bout.toByteArray(), CHARSET);
}
/**
* @return String
*/
public static String pasteTextToTextArea()
{
final Clipboard clipboard = Toolkit.getDefaultToolkit()
.getSystemClipboard();
final DataFlavor flavor = DataFlavor.stringFlavor;
if (!clipboard.isDataFlavorAvailable(flavor))
{
return "";
}
try
{
return (String) clipboard.getData(flavor);
}
catch (UnsupportedFlavorException | IOException e)
{
e.printStackTrace();
}
return "";
}
/**
* @param filename
* @return
*/
public static String load(String filename)
{
return load(new File(filename));
}
@SuppressWarnings({ "javadoc", "resource" })
public static String load(File file)
{
if (file == null || !file.exists())
{
return "";
}
String content = "";
try
{
content = IOUtils.toString(new FileInputStream(file), StandardCharsets.ISO_8859_1);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return content;
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]