Created
November 13, 2023 16:18
-
-
Save ejmudrak/3b36d9e8031249c77007ff2a519d4222 to your computer and use it in GitHub Desktop.
Add Alt Text
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
| # add_alt_text.py | |
| # import utils to load required shared libraries | |
| from utils import inputPath, outputPath | |
| from pdfixsdk.Pdfix import * | |
| def AddAltText(page:PdfPage): | |
| pDoc = page.GetDoc() | |
| content = page.GetContent() | |
| for i in range(content.GetNumObjects()): | |
| page_obj = content.GetObject(i) | |
| content_mark = page_obj.GetContentMark() | |
| is_image = type(page_obj) is PdsImage | |
| if is_image: | |
| # remove existing MCID | |
| page_obj.RemoveTags(kContentMarkMcid) | |
| # add alt text to object | |
| figure_dict = pDoc.CreateDictObject(False) | |
| figure_dict.RemoveKey('Alt') | |
| figure_dict.PutString("Alt", "This is some alt text") | |
| print("Alt text: ", figure_dict.GetText("Alt")) | |
| content_mark.AddTag("Figure", figure_dict, False) | |
| page.SetContent() | |
| pdfix = GetPdfix() | |
| if pdfix is None: | |
| raise Exception('Pdfix Initialization fail') | |
| doc = pdfix.OpenDoc("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()) | |
| for i in range(doc.GetNumPages()): | |
| page = doc.AcquirePage(i) | |
| AddAltText(page) | |
| page.Release() | |
| if not doc.Save("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