Created
November 16, 2023 15:21
-
-
Save ejmudrak/7d51bcfd439f17667fc19165dd4ee4f6 to your computer and use it in GitHub Desktop.
Set Alt Text (via document the structure tree)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # set_alt_text.py | |
| # import utils to load required shared libraries | |
| from utils import inputPath, outputPath | |
| from pdfixsdk.Pdfix import * | |
| # sets alt text on nested figures | |
| def SetNestedAltText(struct_elem: PdsStructElement): | |
| for i in range(struct_elem.GetNumChildren()): | |
| # search nested child struct elements | |
| if struct_elem.GetChildType(i) == kPdsStructChildElement: | |
| child_obj = struct_elem.GetChildObject(i) | |
| child_elem = struct_elem.GetStructTree().GetStructElementFromObject(child_obj) | |
| if child_elem is None: | |
| raise Exception(pdfix.GetError()) | |
| type = child_elem.GetType(True) | |
| if type == 'Figure': | |
| child_elem.SetAlt('This is a decorative image') | |
| table = SetNestedAltText(child_elem) | |
| if table is not None: | |
| return table | |
| return None | |
| # starts with root document element and works down | |
| def SetAltText(struct_tree: PdsStructTree): | |
| for i in range(struct_tree.GetNumChildren()): | |
| child_obj = struct_tree.GetChildObject(i) | |
| child_elem = struct_tree.GetStructElementFromObject(child_obj) | |
| paragraph = SetNestedAltText(child_elem) | |
| if paragraph is not None: | |
| return paragraph | |
| return None | |
| pdfix = GetPdfix() | |
| if pdfix is None: | |
| raise Exception('Pdfix Initialization fail') | |
| doc = pdfix.OpenDoc(inputPath + "/test.pdf", "") | |
| if doc is None: | |
| raise Exception('Unable to open pdf : ' + pdfix.GetError()) | |
| # preflight document for better tagging structure (optional) | |
| tmpl = doc.GetTemplate() | |
| for i in range(0, doc.GetNumPages()): | |
| tmpl.AddPage(i, 0, None) | |
| tmpl.Update(0, None) | |
| # set the document title and language | |
| title = "Supplemental Document" | |
| lang = "en-US" | |
| # run make accessibile | |
| accessibleParams = PdfAccessibleParams() | |
| if not doc.MakeAccessible(accessibleParams, title, lang, 0, None): | |
| raise Exception(pdfix.GetError()) | |
| struct_tree = doc.GetStructTree() | |
| if not struct_tree: | |
| raise Exception('No struct tree found') | |
| SetAltText(struct_tree) | |
| if not doc.Save(outputPath + "/alt_text.pdf", kSaveFull): | |
| raise Exception(pdfix.GetError()) | |
| doc.Close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment