Aspose.PDF add watermark error

error:Proxy error(NullReferenceException): Object reference not set to an instance of an object.
code:

        doc = ap.Document(str(file_path))
        artifact = ap.WatermarkArtifact()
        ts = ap.text.TextState()
        ts.font_size = 50
        ts.foreground_color = ap.Color.blue
        ts.font = ap.text.FontRepository.open_font(font_path)
        artifact.set_text_and_state(watermark, ts)
        artifact.artifact_horizontal_alignment = ap.HorizontalAlignment.CENTER
        artifact.artifact_vertical_alignment = ap.VerticalAlignment.CENTER
        artifact.rotation = 45
        artifact.opacity = 0.5
        artifact.is_background = False
        for item in doc.pages:
            item.artifacts.append(artifact)
        doc.save(str(new_file_path))

error code line: item.artifacts.append(artifact)

@David_Matin

Cause

The NullReferenceException you are encountering typically indicates that an object you are trying to use has not been initialized. In your case, this error occurs when you attempt to append the artifact to item.artifacts. This could be due to the artifact not being properly created or initialized.

Solution

  1. Check Artifact Initialization: Ensure that the WatermarkArtifact and TextState objects are correctly initialized. If any of the properties you are trying to set are null, it could lead to this exception.

  2. Verify Font Path: Make sure that the font_path you are using to open the font is valid and that the font file exists. If the font cannot be loaded, it may cause the TextState to not be properly initialized.

  3. Check Document Pages: Ensure that the doc.pages collection is not empty. If there are no pages in the document, trying to append artifacts will lead to issues.

Code

Here’s a modified version of your code with additional checks:

doc = ap.Document(str(file_path))

# Ensure the document has pages
if not doc.pages:
    raise Exception("The document has no pages.")

artifact = ap.WatermarkArtifact()
ts = ap.text.TextState()

# Check if the font is loaded correctly
try:
    ts.font = ap.text.FontRepository.open_font(font_path)
except Exception as e:
    raise Exception(f"Failed to load font: {e}")

ts.font_size = 50
ts.foreground_color = ap.Color.blue
artifact.set_text_and_state(watermark, ts)
artifact.artifact_horizontal_alignment = ap.HorizontalAlignment.CENTER
artifact.artifact_vertical_alignment = ap.VerticalAlignment.CENTER
artifact.rotation = 45
artifact.opacity = 0.5
artifact.is_background = False

# Append artifact to each page
for item in doc.pages:
    item.artifacts.append(artifact)

doc.save(str(new_file_path))

Next Steps

  1. Run the modified code and check if the error persists.
  2. If the error continues, add logging or print statements to identify which part of the code is failing.
  3. Ensure that all paths (file and font) are correct and accessible.

Please try these steps and let me know if you need further assistance!