Converting TIF to PDF via Invoke Code Activity

Hi everyone!

I’m trying to convert a tif file with multiple pages. However, I always get this error when invoking the code. I’m using VB here.

Invoke Code: Exception has been thrown by the target of an invocation.

Below is the complete error message

RemoteException wrapping System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> RemoteException wrapping System.NotSupportedException: No data is available for encoding 1252. For information on defining a custom encoding,
see the documentation for the Encoding.RegisterProvider method.
at System.Text.Encoding.GetEncoding(Int32 codepage)
at PdfSharp.Pdf.Internal.PdfEncoders.get_WinAnsiEncoding()
at PdfSharp.Pdf.Internal.DocEncoding.GetByteCount(Char chars,
Int32 index,
Int32 count)
at System.Text.Encoding.GetByteCount(String s)
at System.Text.Encoding.GetBytes(String s)
at PdfSharp.Pdf.IO.PdfWriter.WriteDocString(String text)
at PdfSharp.Pdf.PdfDate.WriteObject(PdfWriter writer)
at PdfSharp.Pdf.PdfDictionary.WriteDictionaryElement(PdfWriter writer,
PdfName key)
at PdfSharp.Pdf.PdfDictionary.WriteObject(PdfWriter writer)
at PdfSharp.Pdf.PdfDocument.DoSave(PdfWriter writer)
at PdfSharp.Pdf.PdfDocument.Save(Stream stream,
Boolean closeStream)
at PdfSharp.Pdf.PdfDocument.Save(Stream stream)
at PdfSharp.Pdf.PdfDocument.Save(String path)
at UiPathCodeRunner_b37dc930bab84f9aa04c1e9b2488df23.Run()
— End of inner exception stack trace —
at System.RuntimeMethodHandle.InvokeMethod(Object target,
Span1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args) at UiPath.Activities.System.Utilities.InvokeCode.CompilerRunner.Run(Object[] args) at UiPath.Activities.System.Utilities.InvokeCode.NetCodeInvoker.Run(String userCode, List1 inArgs,
IEnumerable`1 imps,
Object args)
at UiPath.Core.Activities.InvokeCode.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance,
ActivityExecutor executor,
BookmarkManager bookmarkManager)
at System.Activities.ActivityInstance.Execute(ActivityExecutor executor,
BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor,
BookmarkManager bookmarkManager,
Location resultLocation)

Here’s my code inside the invoke activity

 Dim tifFilePath As String = "C:\Users\folder\sometif.tif"
 Dim tifBitmap As New Bitmap(tifFilePath)

 'Create a PDF document
 Dim pdfDocument As New Pdf.PdfDocument()

  'Get the GUID for the frame dimension of pages
  Dim frameDimensionGuid As System.Drawing.Imaging.FrameDimension = System.Drawing.Imaging.FrameDimension.Page

   For pageIndex As Integer = 0 To tifBitmap.GetFrameCount(frameDimensionGuid) - 1
       tifBitmap.SelectActiveFrame(frameDimensionGuid, pageIndex)

       Dim memoryStream As New MemoryStream()
       tifBitmap.Save(memoryStream, ImageFormat.Tiff)
       Dim pdfPage As Pdf.PdfPage = pdfDocument.AddPage()
       Dim gfx As XGraphics = XGraphics.FromPdfPage(pdfPage)
       Dim xImage As XImage = XImage.FromStream(memoryStream)

       gfx.DrawImage(xImage, 0, 0, pdfPage.Width, pdfPage.Height)
   Next

   ' Save the PDF file
   Dim outputPdfPath As String = "C:\Users\outputfolder\newpdf.pdf"
   pdfDocument.Save(outputPdfPath)

My Imports
PDfSharp
PdfSharp.Drawing
PdfSharp.Pdf
System.Drawing

The package I installed
image

Now, what’s weird is that I have the same code using Visual Studio and I did not encounter any error.

image

The code in VS studio works and I was able to convert tif with multiple pages into 1 pdf file. I ran out of ideas or solutions why in UiPath invoke code did not work.

Does any one encounter this?

@Lee_Phay_Kho

Try using a different pdfsharp package and check if the issus resolves…

Cheers

Thanks, @Anil_G for the advice! I’ve tried the other pdf sharp package but none worked. However, after some additional googling, I was able to make it work. I found the answer here

https://forum.uipath.com/t/invoke-code-not-finding-codepagesencodingprovider-class-of-system-text-after-migrating-to-6-0/496979

… and below is the overall look of the code. Just sharing it for future reference :slight_smile:

image

image

1 Like

Hi @Lee_Phay_Kho

Try this:
Make sure to Import these from Import NameSpaces.

Imports System.Drawing
Imports System.Drawing.Imaging
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf
Imports System.IO

Try this Invoke Code:

Dim tifFilePath As String = "C:\Users\folder\sometif.tif"
Dim tifBitmap As New Bitmap(tifFilePath)

'Create a PDF document
Dim pdfDocument As New Pdf.PdfDocument()

'Get the GUID for the frame dimension of pages
Dim frameDimensionGuid As System.Drawing.Imaging.FrameDimension = System.Drawing.Imaging.FrameDimension.Page

For pageIndex As Integer = 0 To tifBitmap.GetFrameCount(frameDimensionGuid) - 1
    tifBitmap.SelectActiveFrame(frameDimensionGuid, pageIndex)

    Dim memoryStream As New MemoryStream()
    tifBitmap.Save(memoryStream, ImageFormat.Tiff)

    memoryStream.Position = 0 ' Reset the position to the beginning of the stream.

    Dim pdfPage As Pdf.PdfPage = pdfDocument.AddPage()
    Dim gfx As XGraphics = XGraphics.FromPdfPage(pdfPage)
    Dim xImage As XImage = XImage.FromStream(memoryStream)

    gfx.DrawImage(xImage, 0, 0, pdfPage.Width, pdfPage.Height)

    memoryStream.Dispose() ' Dispose the MemoryStream after each iteration.
Next

'Save the PDF file
Dim outputPdfPath As String = "C:\Users\outputfolder\newpdf.pdf"
pdfDocument.Save(outputPdfPath)

Hope it helps!!

Hi, thank you for your response. I was able to make it work though. I’ll keep your response for future reference. Thank you :smiley:

Hi @Lee_Phay_Kho ,

We would like to know the solution used by you :slight_smile: , So if you could mention the Steps or method used, it will be helpful for others who also get the same issue.

So that you can indicate your method as the solution and close the Topic. If you did find the suggestions provided here as the solution, do mark them as the solution.

Both codes give a bunch of errors. Does anybody have a xaml as example?

Could not find these 2 imports in imports panel:
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf

getting error as
PdfDocument not defined
XImage not defined
PdfPage not defined
XGraphics not defined

Kindly assist

Did you install the PDFSharp-GDI package?

Also, instead of doing imports you can just type the full type reference.

In other words, instead of “Dim pdfDocument As New Pdf.PdfDocument” you can type out the reference “Dim pdfDocument As New PdfSharp.Pdf.PdfDocument”

Hello @postwick, where can I find PDFSharp-GDI package?

There is no such package when I search for it, can you please guide?

Here’s the VB code:

Dim tifFilePath As String = str_tifFilePath
Dim tifBitmap As New Bitmap(tifFilePath)

'Create a PDF document
Dim pdfDocument As New Pdf.PdfDocument()

'Get the GUID for the frame dimension of pages
Dim frameDimensionGuid As System.Drawing.Imaging.FrameDimension = System.Drawing.Imaging.FrameDimension.Page

For pageIndex As Integer = 0 To tifBitmap.GetFrameCount(frameDimensionGuid) - 1
tifBitmap.SelectActiveFrame(frameDimensionGuid, pageIndex)

Dim memoryStream As New MemoryStream()
tifBitmap.Save(memoryStream, ImageFormat.Tiff)

memoryStream.Position = 0 ' Reset the position to the beginning of the stream.

Dim pdfPage As Pdf.PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(pdfPage)
Dim xImage As XImage = XImage.FromStream(memoryStream)

gfx.DrawImage(xImage, 0, 0, pdfPage.Width, pdfPage.Height)

memoryStream.Dispose() ' Dispose the MemoryStream after each iteration.

Next

'Save the PDF file
Dim outputPdfPath As String = str_outputPdfPath
pdfDocument.Save(outputPdfPath)

I am getting this error, while I try to use the above code with arguments (str_tifFilePath, str_outputPdfPath) as below

Error Message:

No compiled code to run
error BC30002: Type ‘Pdf.PdfDocument’ is not defined. At line 4
error BC30002: Type ‘Pdf.PdfPage’ is not defined. At line 17
error BC30002: Type ‘XGraphics’ is not defined. At line 18
error BC30451: ‘XGraphics’ is not declared. It may be inaccessible due to its protection level. At line 18
error BC30002: Type ‘XImage’ is not defined. At line 19 Variable ‘Pdf.PdfDocument’ is missing. Please use Data Manager to recreate it.

The errors are because you don’t have the package installed.

image

Once installed it should look like this:

image

Thanks for replying!

I do not see it in the manage Packages, do I need to download it from somewhere?
please guide.

I am using Studio 2024.10.12 LTS (Enterprise License -Service mode installation)

Do not search PDFSharp-GDI. Search PDFsharp and then look for the one named “PDFsharp for Windows Forms apps” and “by PDFsharp”. Make sure you specifically install the one named “for Windows Forms apps” as you will get multiple results just from searching PDFsharp.

Also, you have a filter set in your Manage Packages window. Remove that filter to make sure you see all results.

Thank you! There are no errors but when I try to run it, it gives out error

Invoke Code: No compiled code to run
error BC30389: ‘UiPath.UIAutomationNext.Enums.ImageFormat’ is not accessible in this context because it is ‘Friend’. At line 13

This is code for reference:

Dim tifFilePath As String = str_tifFilePath
Dim tifBitmap As New Bitmap(tifFilePath)

'Create a PDF document
Dim pdfDocument As New Pdf.PdfDocument()

'Get the GUID for the frame dimension of pages
Dim frameDimensionGuid As System.Drawing.Imaging.FrameDimension = System.Drawing.Imaging.FrameDimension.Page

For pageIndex As Integer = 0 To tifBitmap.GetFrameCount(frameDimensionGuid) - 1
tifBitmap.SelectActiveFrame(frameDimensionGuid, pageIndex)

Dim memoryStream As New MemoryStream()
tifBitmap.Save(memoryStream, ImageFormat.Tiff)

memoryStream.Position = 0 ' Reset the position to the beginning of the stream.

Dim pdfPage As Pdf.PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(pdfPage)
Dim xImage As XImage = XImage.FromStream(memoryStream)

gfx.DrawImage(xImage, 0, 0, pdfPage.Width, pdfPage.Height)

memoryStream.Dispose() ' Dispose the MemoryStream after each iteration.

Next

'Save the PDF file
Dim outputPdfPath As String = str_outputPdfPath
pdfDocument.Save(outputPdfPath)

You’re DIMing variables like tifFilePath and outputPdfPath but then not assigning them values. You should be providing those as arguments to the Invoke Code, then you don’t DIM them.

Here is the exact code I use to convert a TIF to a PDF:

Try
Dim MyImage As System.Drawing.Image = System.Drawing.Image.FromFile(sourcefile)
Dim doc As PDFSharp.Pdf.PdfDocument = New PDFSharp.Pdf.PdfDocument()

For PageIndex As Integer = 0 To MyImage.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page) - 1
	MyImage.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, PageIndex)
	Dim img As PdfSharp.Drawing.XImage = PdfSharp.Drawing.XImage.FromGdiPlusImage(MyImage)
	Dim page As PdfSharp.Pdf.PdfPage = New PdfSharp.Pdf.PdfPage
	page.Orientation = PdfSharp.PageOrientation.Portrait
	page.Width = PdfSharp.Drawing.XUnit.FromInch(MyImage.Width / MyImage.HorizontalResolution)
	page.Height = PdfSharp.Drawing.XUnit.FromInch(MyImage.Height / MyImage.VerticalResolution)
	doc.Pages.Add(page)
	Dim xgr As PdfSharp.Drawing.XGraphics = PdfSharp.Drawing.XGraphics.FromPdfPage(doc.Pages(PageIndex))
	xgr.DrawImage(img, 0, 0)
Next

doc.Save(destinationfile)
doc.Close()
MyImage.Dispose()
Catch ex As Exception
	Console.WriteLine(ex)
End Try

It gives no error, but it doesn’t produce any pdf file

In the logs, it shows as memory out of exception and also attached arguments for reference

===================================================================================================
System.OutOfMemoryException: Out of memory.
at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
at UiPathCodeRunner_15d4b7687942454998c48bdbc81f9699.Run(String sourcefile, String destinationfile)

=====================================================================================================

How large is your TIF file?

It ranges from 171Kb to 1189 kb

How large was the file that gave you the out of memory exception? Are you just testing with one file at a time? Or are you looping through all those files? Did it do any successfully?

I have tested it for one file of 171kb