[英]C#: Saving iText7 PDFs into a folder chosen by the user with a dialog
我将在 C# 和 Windows forms 中制作一个简单的程序,它通过一些文本框获取用户提供的一些数据,当他按下一个按钮时,会显示一个dialog
(我不知道), pc 文件夹并选择一个保存位置。
好吧,我使用了一个FolderBrowserDialog
(我不知道这是否是正确的),但是有一个问题:为了使用 itext7 存储 PDF,我必须给出一个Environment.SpecialFolder
变量,而方法selectedPath()
获取formBrowserDialog的用户路径,返回一个字符串。
我试图以某种方式将string
转换为Environment.SpecialFolder
,但我总是得到一个System.ArgumentException
这是我的代码:
string name = txtName.Text;
//
//bla bla bla getting the parameters given by the user
//...
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
string folder="";
//"fbd" is the FolderBrowserDialog
if (fbd.ShowDialog() == DialogResult.OK)
{
//here I get the folder path (I hope I've chosen the right dialog for this scope, which is a FolderBrowserDialog)
folder = fbd.SelectedPath;
//starting my pdf generation
//here is my attempt to write something in order to parse the path string into an Environment.SpecialFolder type, to use it as a parameter in getFolderPath()
Environment.SpecialFolder path = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), folder);
//here it's supposed to give to the GetFolderPath method the Environment.SpecialFolder type.
var exportFolder = Environment.GetFolderPath(path); //ON THIS LINE I GET THE EXCEPTION
var exportFile = System.IO.Path.Combine(exportFolder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("
//bla bla bla writing my things on it
"));
}
}
//pdf creation ends
}
为了简化这一切,您根本不需要Environment.SpecialFolder
变量,也不需要将其作为参数传递。
引发异常的原因是因为您尝试将string
解析为Environment.SpecialFolder
变量enum
,而该字符串无法解析为一个。
您可以在这里查看包含的枚举列表。 我敢打赌,您选择的特定路径与这些都不匹配。
这是您的代码当前正在执行的操作:
enum
Environment.SpecialFolder
变量相关联的字符串(因此,如果您实际上能够解析它,那么您最终会得到刚开始的内容)您可以通过省略导致错误的步骤 2 和 3 来简化所有这些操作。
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
//You select the folder here
if (fbd.ShowDialog() == DialogResult.OK)
{
string folder = fbd.SelectedPath;
//combine the path of the folder with the pdf name
string exportFile = System.IO.Path.Combine(folder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("//bla bla bla writing my things on it"));
}
}
//Pdf creation ends
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.