Biblioteca para editar archivos pdf con C# en UWP

Estoy creando una aplicación para UWP (aplicación universal de Windows 10) con C#/XAML. es una aplicación de liberación de modelo / liberación de propiedad. Así que tengo la siguiente plantilla.

Haga clic aquí para ver la plantilla

Quiero hacer lo siguiente con C#

  1. Lea el archivo pdf de la plantilla.
  2. Complete la información del formulario como (nombre, edad, etc.).
  3. Inserte una imagen en la esquina superior derecha (como se ve en la plantilla) guarde el archivo pdf en una nueva ubicación.

Ya probé syncfusion api para pdf, pero no es compatible con el proyecto UWP .NET CORE por algún motivo.

Por favor, hágame saber si hay alguna biblioteca para esta tarea. Realmente agradeceré cualquier tipo de ayuda.

Respuestas (2)

Syncfusion Essential PDF para UWP también es compatible con .NET Core. Pruebe este código de muestra .

            //Loading Pdf and image to stream

         Stream jpegImage = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("templateForm.DataUWP.images.png");
        Stream  docStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("templateForm.DataUWP.Form.pdf");


        PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream);

        //Draw image 

        PdfImage img = new PdfBitmap(jpegImage);

        loadedDocument.Pages[0].Graphics.DrawImage(img, new PointF(380, 90), new SizeF(100, 100));

        //Get the loaded form.

        PdfLoadedForm loadedForm = loadedDocument.Form;

        PdfLoadedFormFieldCollection fieldCollection = loadedForm.Fields as PdfLoadedFormFieldCollection;

        PdfLoadedField loadedField = null;

        // Get the field using TryGetField Method and fill it.


        if (fieldCollection.TryGetField("name", out loadedField))

        {

            (loadedField as PdfLoadedTextBoxField).Text = "John";

        }

        //Save the modified document.
        MemoryStream streamOut = new MemoryStream();
        loadedDocument.Save(streamOut);

        //Close the document

        loadedDocument.Close(true);

        //Save document to file
        Save(streamOut, "sample.pdf");

La biblioteca XFINIUM.PDF es compatible con Windows 10 UWP.
Su plantilla no incluye ningún campo, así que la modifiqué. El código para llenar el formulario se ve así:

private Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;

private async void btnFillDocumentTemplate_Click(object sender, RoutedEventArgs e)
{
    Stream pdfStream = assembly.GetManifestResourceStream("UWP_FillDocumentTemplate.ModelReleaseTemplate.pdf");
    PdfFixedDocument document = new PdfFixedDocument(pdfStream);
    pdfStream.Dispose();

    // Fill photographer info
    document.Form.Fields["PhotographerName"].Value = "John Doe";
    document.Form.Fields["PhotographerDateSigned"].Value = "09/03/2017";
    document.Form.Fields["PhotographerShootDate"].Value = "08/03/2017";
    document.Form.Fields["PhotographerShootCountry"].Value = "Italy";
    document.Form.Fields["PhotographerShootDescription"].Value = "Tuscany";
    // Draw photographer signature
    DrawImageAtFieldLocation(document.Form.Fields["PhotographerSignature"].Widgets[0], "PhotographerSignature.png");

    // Fill model info
    document.Form.Fields["ModelName"].Value = "Jane Doe";
    document.Form.Fields["ModelDOB"].Value = "01/01/1980";
    document.Form.Fields["ModelGender"].Value = "Male";
    document.Form.Fields["ModelAddress1"].Value = "via Romana no 1";
    document.Form.Fields["ModelCity"].Value = "Rome";
    document.Form.Fields["ModelState"].Value = "Rome";
    document.Form.Fields["ModelCountry"].Value = "Italy";
    document.Form.Fields["ModelZip"].Value = "12345";
    document.Form.Fields["ModelPhone"].Value = "0123456789";
    document.Form.Fields["ModelEmail"].Value = "jane.doe@nomail.com";
    document.Form.Fields["ModelDateSigned"].Value = "09/03/2017";
    document.Form.Fields["ModelParentName"].Value = "Parent Jane Doe";
    // Draw model signature
    DrawImageAtFieldLocation(document.Form.Fields["ModelSignature"].Widgets[0], "ModelSignature.png");
    // Draw model visual
    DrawImageAtFieldLocation(document.Form.Fields["ModelVisualReference"].Widgets[0], "XFINIUM.PDF.png");

    // Fill ethnicity
    (document.Form.Fields["EthnicityAsian"] as PdfCheckBoxField).Checked = true;

    // Fill witness info
    document.Form.Fields["WitnessName"].Value = "Witness John Doe";
    document.Form.Fields["WitnessDateSigned"].Value = "09/03/2017";
    // Draw photographer signature
    DrawImageAtFieldLocation(document.Form.Fields["WitnessSignature"].Widgets[0], "WitnessSignature.png");

    // If you want to prevent changes to filled data, you can flatten the form fields.
    document.Form.FlattenFields();

    // Save the filled form
    FileSavePicker fileSavePicker = new FileSavePicker();
    fileSavePicker.FileTypeChoices.Add("PDF files", new List<string>() { ".pdf" });
    fileSavePicker.SuggestedFileName = "ModelReleaseFilled";

    var outputFile = await fileSavePicker.PickSaveFileAsync();
    if (outputFile != null)
    {
        var destPdfStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);
        using (Stream stm = destPdfStream.AsStream())
        {
            document.Save(stm);
            await stm.FlushAsync();
        }
        destPdfStream.Dispose();
    }
}

private void DrawImageAtFieldLocation(PdfFieldWidget fieldWidget, string imageName)
{
    Stream imageStream = assembly.GetManifestResourceStream("UWP_FillDocumentTemplate." + imageName);
    PdfPngImage image = new PdfPngImage(imageStream);
    PdfVisualRectangle fieldRect = fieldWidget.VisualRectangle;
    // Draw the image on the page where the field widget is located.
    fieldWidget.Page.Graphics.DrawImage(image,
        fieldRect.Left, fieldRect.Top, fieldRect.Width, fieldRect.Height);

    imageStream.Dispose();
}

Puede descargar el formulario completo y el proyecto de muestra .
Descargo de responsabilidad: trabajo para la empresa que desarrolla esta biblioteca.

muchas gracias, ¿puede decirme cómo modificó el archivo para incluir campos?
@touseef Usé Adobe Acrobat para agregar los campos de formulario.
¿También puede mostrarme una forma de agregar un texto personalizado tomado del usuario y reemplazar el texto (escritura del acuerdo) en la plantilla pdf?
PDF es un formato fijo, por lo que reemplazar texto no genera una recreación del diseño de página, como en MS Word. Si reemplaza el texto, el nuevo texto puede superponerse al texto que lo rodea o pueden aparecer grandes espacios en el texto. Todavía no admitimos el reemplazo de texto.