AL code for Import pdf document file from sharing path into table

 To import a PDF document file from a shared path into a table using AL code in Microsoft Dynamics 365 Business Central, you can utilize the `FileManagement` codeunit to copy the file from the shared path to a temporary folder, and then use the `InStream` data type to import the contents of the file into a table field. Here's an example:


```AL

PROCEDURE ImportPDFDocumentFromFile@1()

VAR

  FileManagement@1: Codeunit 419;

  TempFolderPath@2: Text[250];

  SourceFilePath@3: Text[250];

  PDFDocument@4: Record 50000;

  InStream@5: InStream;

  PDFContent@6: Text;

BEGIN

  // Shared path of the PDF document file

  SourceFilePath := '\\server\share\document.pdf';

  

  // Create a temporary folder to store the file

  TempFolderPath := FileManagement.GetTempPath;

  FileManagement.CreateDirectory(TempFolderPath);

  

  // Copy the file from shared path to temporary folder

  FileManagement.CopyFile(SourceFilePath, TempFolderPath + 'document.pdf');

  

  // Open the file as an InStream

  InStream.OPEN(TempFolderPath + 'document.pdf');

  

  // Read the content of the file into a Text variable

  InStream.READTEXT(PDFContent);

  

  // Close the InStream

  InStream.CLOSE;

  

  // Assign the content to the table field

  PDFDocument.INIT;

  PDFDocument."PDF Content" := PDFContent;

  PDFDocument.INSERT(TRUE);

  

  // Delete the temporary file and folder

  FileManagement.DeleteFile(TempFolderPath + 'document.pdf');

  FileManagement.DeleteDirectory(TempFolderPath, TRUE);

END;

```


In this example, we use the `FileManagement` codeunit to perform file-related operations. First, we set the shared path of the PDF document file in the `SourceFilePath` variable. Then, we create a temporary folder using the `GetTempPath` method and `CreateDirectory` method of the `FileManagement` codeunit.


Next, we copy the file from the shared path to the temporary folder using the `CopyFile` method of the `FileManagement` codeunit.


After that, we open the file as an `InStream` using the `OPEN` method. We then use the `READTEXT` method to read the content of the file into a `Text` variable (`PDFContent` in this example).


We close the `InStream` using the `CLOSE` method.


Finally, we initialize the target table (`PDFDocument` in this example), assign the PDF content to the desired field (`"PDF Content"` in this example), and insert the record into the table.


Make sure to adjust the code based on the table structure and field names in your scenario.


Additionally, we delete the temporary file and folder using the `DeleteFile` and `DeleteDirectory` methods of the `FileManagement` codeunit.


Ensure that the shared path is accessible from the server running Business Central and that the necessary permissions are set for accessing the shared folder.

No comments:

Post a Comment