Megrahi said he wanted to spend his final days with his family
Details of the Lockerbie bomber's personal plea for compassion and his medical notes have been disclosed.
In a letter, he told Justice Secretary Kenny MacAskill: "I am terminally ill. There is no prospect of my recovery."
The notes - released for the first time - describe a man in increasing pain, whose condition had "declined significantly" in recent weeks.
Confirmation that medics believed he would die within months was backed up in his letter, dated July of this year.
Megrahi said: "My continued incarceration in HMP Greenock is not conducive to my well-being as my life nears its end.
"Whilst everything is being done to make my time here as comfortable as possible, the personnel within the prison are hardly equipped to deal with the many aspects of my terminal illness.
"It is my view that imprisonment is hastening my decline."
He described a poor response to treatment, stating that the disease was "burgeoning and spreading rapidly".
He called on Mr MacAskill to consider compassionate release - which was granted on Thursday - saying he was likely to die before the end of the year.
The bomber asked to be reunited with his family and restated his belief that he had been wrongly convicted.
He wrote: "It would be my wish to return to my family to spend the short time that I have left with them.
"I am a family man: first and foremost I am a son, husband, father and grandfather.
The Libyan said being in Greenock Prison was hastening his decline
"I have been separated from my family as a result of what I consider to be an unjust conviction.
"I have tried to bear that with a degree of equanimity and dignity."
A report dated 10 August from the director of health and care for the Scottish Prison Service disclosed the full extent of his illness.
It said that Megrahi was suffering from "metastatic prostate cancer", general debility, and several symptoms directly relating to his condition.
"As a result, his sleep pattern is disturbed," the report said.
"He appears tired and drawn.
"His recent consumption of appropriate medicines to assist him has increased."
Megrahi underwent specialist consultations with a "variety" of medics from across the UK and Libya.
In light of medical notes taken in June and July, the report added: "Reviewing the total picture, the concluding specialist view is that, in the absence of a good response to treatment, survival could be in the order of 'months' and, no longer 'many months'.
"Whether or not prognosis is more or less than three months, no specialist 'would be willing to say'."
It added: "Whilst his condition does not restrict or remove Mr Megrahi's ability to carry out any particular tasks, we do not believe he would represent a risk to himself or anyone else."