生成pdf文件后如何保存此pdf的动态名称? [英] After generating pdf file how to save dynamic name for this pdf?
问题描述
我使用文件路径生成PDF文档,以创建名称为 test.PDF
的PDF文件。但是,我希望这样做,以便用户可以选择一个名称,并在PDF生成时使用此名称。我正在使用iText创建这样的PDF文件。
I generate a PDF document using a file path to create a PDF file with name test.PDF
. However, I want to chance this so that the user can choose a name and that this name is used at the time of PDF generation. I am using iText to creating a PDF file like this.
private String FILE = "e://test.PDF";
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
// add content
document.close();
如何更改此项以便使用最终用户选择的文件名保存文件?
How do I change this so that the file is saved using the file name chosen by the end user?
推荐答案
我写过这个概念证明,它正如预期的那样完全。当你运行它时,会打开一个 JFrame
:
I have written this proof of concept and it works exactly as expected. When you run it, a JFrame
opens:
JFrame
由 JButton
组成,文字按下ATUL,按下!当您单击此按钮时,会打开一个对话框:
The JFrame
consists of a JButton
with text Push ATUL, push! When you click this button a dialog opens:
我选择一个文件夹( test
)并选择一个文件名( test.pdf
)。然后,我点击保存。这是我文件夹中显示的内容:
I select a folder (test
) and I choose a file name (test.pdf
). Then I click Save. This is what shows up in my folder:
当我打开这个文件时,我看到:
When I open this file, I see:
这是示例的完整代码:
/*
* Example written in answer to:
* http://stackoverflow.com/questions/35669782/
*/
package sandbox.objects;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
* @author Bruno Lowagie (iText Software)
*/
public class PdfOnButtonClick {
public class PdfActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser dialog = new JFileChooser();
int dialogResult = dialog.showSaveDialog(null);
if (dialogResult==JFileChooser.APPROVE_OPTION){
String filePath = dialog.getSelectedFile().getPath();
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
document.add(new Paragraph("File with path " + filePath));
document.close();
}
catch(DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setTitle("ATUL doesn't know how to code");
frame.setResizable(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button = new JButton("Push ATUL, push!");
button.addActionListener(new PdfOnButtonClick().new PdfActionListener());
frame.getContentPane().add(button);
frame.setVisible(true);
}
}
这篇关于生成pdf文件后如何保存此pdf的动态名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!