Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Manipular campos de formulários dentro de documentos PDF pode ser crucial ao lidar com operações de entrada e saída de dados em várias aplicações. A biblioteca Aspose.PDF oferece uma funcionalidade robusta para exportar e importar campos de formulários no formato JSON. Abaixo, exploramos vários trechos de código que demonstram como realizar essas tarefas usando diferentes abordagens.
Desde a versão 24.7, é possível adicionar Importação e Exportação de Dados de Formulários em Formato JSON:
Essa abordagem exporta todos os campos de formulários de um documento PDF existente para um arquivo JSON e os importa para um novo documento PDF.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportAllFieldsToJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// Create ExportFieldsToJsonOptions with indentation
var options = new Aspose.Pdf.ExportFieldsToJsonOptions { WriteIndented = true };
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Export fields to JSON
var exportResult = document.Form.ExportToJson(outputJsonPath, options);
// Optionally, save the document with fields to a new PDF
document.Save(dataDir + "TextBox_out.pdf");
}
}
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldsFromJsonAndInsertToPdf(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Create PDF document to import fields into
var newDocument = new Aspose.Pdf.Document();
// Add page
var page = newDocument.Pages.Add();
// Import fields from JSON
var importResult = newDocument.Form.ImportFromJson(outputJsonPath);
// Save PDF document
newDocument.Save(dataDir + "TextBox_out.pdf");
}
}
Esse trecho exporta campos para o arquivo JSON utilizando ‘FileStream’ para gerenciar a entrada e saída do arquivo.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportFieldsToJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Create ExportFieldsToJsonOptions with indentation
var options = new Aspose.Pdf.ExportFieldsToJsonOptions { WriteIndented = true };
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Create a FileStream to write the JSON output
using (var fileStream = File.Create(outputJsonPath))
{
// Export fields to JSON using the FileStream
var exportResult = document.Form.ExportToJson(fileStream, options);
}
}
}
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldsFromJsonToCreatedPdt(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Create PDF document to import fields into
var newDocument = new Aspose.Pdf.Document();
// Add page
var page = newDocument.Pages.Add();
// Open the JSON file for reading
using (var fileStream = File.OpenRead(outputJsonPath))
{
// Import fields from JSON using the FileStream
var importResult = newDocument.Form.ImportFromJson(fileStream);
}
// Save PDF document
newDocument.Save(dataDir + "TextBox_out.pdf");
}
}
Em alguns cenários, você pode preferir trabalhar com dados na memória em vez de com arquivos no disco. Essa abordagem utiliza ‘MemoryStream’ para lidar com os processos de exportação e importação totalmente na memória.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportFieldsToJsonUsingMemoryStream(string inputPdfPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Create a MemoryStream to hold the JSON data
using (var memoryStream = new MemoryStream())
{
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Export fields to JSON and write to the MemoryStream
var exportResult = document.Form.ExportToJson(memoryStream);
}
// Save the MemoryStream content to a file
File.WriteAllBytes(outputPdfPath, memoryStream.ToArray());
}
}
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldsFromJsonUsingMemoryStream(string inputPdfPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Create PDF document to import fields into
var newDocument = new Aspose.Pdf.Document();
// Add page
var page = newDocument.Pages.Add();
// Create a MemoryStream to hold the JSON data
using (var memoryStream = new MemoryStream())
{
// Export fields from the original document to the MemoryStream
document.Form.ExportToJson(memoryStream);
// Reset the MemoryStream position to the beginning
memoryStream.Position = 0;
// Import fields from the MemoryStream into the new document
var importResult = newDocument.Form.ImportFromJson(memoryStream);
}
// Save PDF document
newDocument.Save(dataDir + "TextBox_out.pdf");
}
}
Às vezes, você pode precisar exportar ou importar apenas um campo específico em vez de todos os campos no documento.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportFieldToJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// Create ExportFieldsToJsonOptions with indentation
var options = new Aspose.Pdf.ExportFieldsToJsonOptions { WriteIndented = true };
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Get the specific field (WidgetAnnotation) from the form
if (document.Form[1] is Aspose.Pdf.Annotations.WidgetAnnotation field)
{
// Export the field to JSON
var exportResult = field.ExportToJson(outputJsonPath, options);
}
}
}
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldFromJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Create PDF document to import fields into
var newDocument = new Aspose.Pdf.Document();
// Add page
var page = newDocument.Pages.Add();
// Import fields from JSON
var importResult = newDocument.Form.ImportFromJson(outputJsonPath);
// Save PDF document
newDocument.Save(dataDir + "TextBox_out.pdf");
}
}
Este exemplo é semelhante ao anterior, mas utiliza ‘FileStream’ para lidar com as operações de exportação e importação de um campo específico.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportFieldToJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// Create ExportFieldsToJsonOptions with indentation
var options = new Aspose.Pdf.ExportFieldsToJsonOptions { WriteIndented = true };
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Get the specific field (WidgetAnnotation) from the form
if (document.Form[1] is Aspose.Pdf.Annotations.WidgetAnnotation field)
{
// Create a FileStream to write the JSON output
using (var fileStream = File.Create(outputJsonPath))
{
// Export the field to JSON using the FileStream
var exportResult = field.ExportToJson(fileStream, options);
}
}
}
}
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldFromJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// Create PDF document to import fields into
using (var newDocument = new Aspose.Pdf.Document())
{
// Add page
var page = newDocument.Pages.Add();
// Open the JSON file for reading
using (var fileStream = File.OpenRead(outputJsonPath))
{
// Import fields from JSON using the FileStream
var importResult = newDocument.Form.ImportFromJson(fileStream);
}
// Save PDF document
newDocument.Save(dataDir + "TextBox_out.pdf");
}
}
Esse trecho de código demonstra como exportar um campo de formulário específico de um documento PDF para o formato JSON usando um ‘MemoryStream’ e, em seguida, importá-lo para um novo documento PDF.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportFieldToJsonUsingMemoryStream(string inputPdfPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Create a MemoryStream to hold the JSON data
using (var memoryStream = new MemoryStream())
{
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Get the specific field (WidgetAnnotation) from the form
if (document.Form[1] is Aspose.Pdf.Annotations.WidgetAnnotation field)
{
// Export the field to JSON and write to the MemoryStream
var exportResult = field.ExportToJson(memoryStream);
}
}
// Optionally, you can save the MemoryStream content to a file
File.WriteAllBytes(outputPdfPath, memoryStream.ToArray());
}
}
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldFromJsonUsingMemoryStream(string inputPdfPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Create PDF document to import fields into
var newDocument = new Aspose.Pdf.Document();
// Add page
var page = newDocument.Pages.Add();
// Create a MemoryStream to hold the JSON data
using (var memoryStream = new MemoryStream())
{
// Export fields from the original document to the MemoryStream
document.Form.ExportToJson(memoryStream);
// Reset the MemoryStream position to the beginning
memoryStream.Position = 0;
// Import fields from the MemoryStream into the new document
var importResult = newDocument.Form.ImportFromJson(memoryStream);
}
// Save PDF document
newDocument.Save(dataDir + "TextBox_out.pdf");
}
}
Esse trecho de código mostra como exportar o valor de um campo de formulário específico de um documento PDF para um arquivo JSON usando FileStream.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportFieldValueToJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Get the specific field from the form
if (document.Form.Fields[1] is Aspose.Pdf.Forms.Field field)
{
// Create a FileStream to write the JSON output
using (var fileStream = File.Create(outputJsonPath))
{
// Export the field value to JSON using the FileStream
field.ExportValueToJson(fileStream);
}
}
}
}
Esse trecho de código demonstra como importar um valor de um arquivo JSON para um campo de formulário específico em um documento PDF usando FileStream.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldValueFromJson(string inputPdfPath, string outputJsonPath, string outputPdfPath)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Get the specific field from the form
if (document.Form.Fields[1] is Aspose.Pdf.Forms.Field field)
{
// Open the JSON file for reading
using (var fileStream = File.OpenRead(outputJsonPath))
{
// Import the field value from JSON using the FileStream
field.ImportValueFromJson(fileStream);
}
}
// Save PDF document
document.Save(dataDir + "TextBox_out.pdf");
}
}
Esse trecho de código demonstra como importar um valor de outro campo para o campo específico do arquivo JSON usando FileStream e Aspose.PDF.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ImportFieldValueFromJson(string inputPdfPath, string outputJsonPath, string outputPdfPath, string fullNameOfOtherFieldInJson)
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "TextField.pdf"))
{
// Get the specific field from the form
if (document.Form.Fields[1] is Aspose.Pdf.Forms.Field field)
{
// Open the JSON file for reading
using (var fileStream = File.OpenRead(outputJsonPath))
{
// Import the field value from JSON using the FileStream and the full name of the other field in JSON
field.ImportValueFromJson(fileStream, fullNameOfOtherFieldInJson);
}
}
// Save PDF document
document.Save(dataDir + "TextBox_out.pdf");
}
}
Este exemplo demonstra como exportar campos de formulários de um PDF para um arquivo JSON usando Aspose.PDF, incluindo o tratamento de diferentes status para cada campo durante o processo de exportação.
Vamos detalhar este exemplo do Aspose.PDF passo a passo:
Carregando o Documento. Carregamos um documento PDF chamado “Sample.pdf” de um diretório especificado.
Definindo Opções de Exportação. Aqui, criamos uma instância de ExportFieldsToJsonOptions com duas configurações:
ExportPasswordValue
: Isso inclui campos de senha na exportação.WriteIndented
: Isso formata a saída JSON para ser indentada para legibilidade.Exportar campos de formulários para JSON. Exportamos os campos de formulários do arquivo PDF para um arquivo JSON chamado “export.json” usando os parâmetros especificados.
Processando Resultados da Exportação: Este loop itera pelos resultados da exportação e imprime o status de cada campo:
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExportFieldsToJsonWithOptions()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Open PDF document
using (var document = new Aspose.Pdf.Document(Path.Combine(dataDir, "Forms", "Sample.pdf")))
{
// Create ExportFieldsToJsonOptions with specific settings
var options = new Aspose.Pdf.ExportFieldsToJsonOptions
{
ExportPasswordValue = true,
WriteIndented = true,
};
var exportResults = document.Form.ExportToJson(File.OpenWrite("export.json"), options);
foreach (var result in exportResults)
{
Console.Write($"{result.FieldFullName} ");
switch (result.FieldSerializationStatus)
{
case Aspose.Pdf.FieldSerializationStatus.Success:
Console.WriteLine("Success");
break;
case Aspose.Pdf.FieldSerializationStatus.Warning:
foreach (var messages in result.WarningMessages)
{
Console.WriteLine(messages);
}
break;
case Aspose.Pdf.FieldSerializationStatus.Error:
foreach (var messages in result.ErrorMessages)
{
Console.WriteLine(messages);
}
break;
}
}
}
}
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.